Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
243 views
in Technique[技术] by (71.8m points)

reactjs - Can you explain the differences between all those ways of passing function to a component?

Just a snippet code in one of React tutorial questions.

What happens when you click each of the buttons?

class App extends React.Component {
  
  constructor() {
    super(); 
    this.name = 'MyComponent';
    
    this.handleClick2 = this.handleClick1.bind(this);
  }
  
  handleClick1() {
    alert(this.name);
  }
  
  handleClick3 = () => alert(this.name);
render() {
    return (
      <div>
        <button onClick={this.handleClick1()}>click 1</button>
        <button onClick={this.handleClick1}>click 2</button>
        <button onClick={this.handleClick2}>click 3</button>
        <button onClick={this.handleClick3}>click 4</button>
      </div>
    );
  }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Well, this and classes is one of the harder subjects to wrap your head around. Perhaps it makes it easier to understand with a few examples.

Take a look at this issue in the React repository. Dan Abramov explains which method Facebook uses internally.

class MyComponent extends React.Component {

  name = 'MyComponent';

  constructor(props) {
    super(props);

    this.handleClick4 = this.handleClick4.bind(this);
  }

  handleClick1() {
    // `this` is not the component instance since this function isn't bound to this class instance.
    alert(this.name); // undefined
  }

  handleClick2() {
    // Using arrow functions we force the context to this component instance.
    alert(this.name); // MyComponent
  }

  handleClick3 = () => {
    // Instead of using class methods, we assign an Arrow function to as a member of this class instance.
    // Since arrow functions are bound automatically to the current context, it's bound to this class instance.
    alert(this.name); // MyComponent
  };

  handleClick4() {
    // We are actually overriding this property with a "bound" version of this method in the constructor.
    alert(this.name); // MyComponent
  }

  render() {
    return (
      <div>
        <button onClick={this.handleClick1}>click 1</button>
        <button onClick={() => this.handleClick2}>click 2</button>
        <button onClick={this.handleClick3}>click 3</button>
        <button onClick={this.handleClick4}>click 4</button>
      </div>
    );
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...