【问题标题】:Can you explain the differences between all those ways of passing function to a component?你能解释一下所有这些将函数传递给组件的方式之间的区别吗?
【发布时间】:2019-06-04 05:37:22
【问题描述】:

只是一个 React 教程问题中的一个 sn-p 代码。

当你点击每个按钮时会发生什么?

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

为什么 click 2 会以它的方式工作?

【问题讨论】:

标签: reactjs


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2012-12-09
    • 2017-06-12
    • 1970-01-01
    • 2020-04-19
    • 2016-07-25
    • 1970-01-01
    • 2011-12-11
    • 1970-01-01
    • 2012-09-22
    相关资源
    最近更新 更多