您能解释一下所有将函数传递给组件的方式之间的区别吗?

时间:2019-01-09 12:30:54

标签: reactjs

在React教程问题之一中只是一个片段代码。

单击每个按钮会发生什么?

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>
    );
  }
}

为什么点击2会起作用?

1 个答案:

答案 0 :(得分:3)

好吧,this和课程是让您难忘的较难主题之一。也许通过一些示例更容易理解。

在React存储库中查看this issue。 Dan Abramov解释了Facebook内部使用哪种方法。

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>
    );
  }
}