为什么我们需要为 JSX 回调绑定"this"



在这个例子中,我们需要将handleClick()的'this'对象绑定到全局范围:

class Toggle extends React.Component {
  constructor(props) {
    super(props);
    this.state = {isToggleOn: true};
    // This binding is necessary to make `this` work in the callback
    this.handleClick = this.handleClick.bind(this);
  }
  handleClick() {
    this.setState(prevState => ({
      isToggleOn: !prevState.isToggleOn
    }));
  }
  render() {
    return (
      <button onClick={this.handleClick}>
        {this.state.isToggleOn ? 'ON' : 'OFF'}
      </button>
    );
  }
}

但是,handleClick() 是在组件的范围内定义的,所以我们不应该为此函数指定 'this' 对象,因为它已经引用了组件本身吗?

你是对的,但你错过了一件事。不绑定到处理程序的this范围是组件。那么,当您想要事件的上下文时会发生什么?你没有它。

解决此问题的另一种方法是按词法绑定组件,这样您就不必担心手动绑定每个函数。

handleClick = () => { //arrow function applied
    this.setState(prevState => ({
        isToggleOn: !prevState.isToggleOn
    }));
}

请注意,现在您现在也不再需要组件构造函数了。

constructor(props) {
    super(props);
    this.state = {isToggleOn: true};
    // This binding is necessary to make `this` work in the callback
    this.handleClick = this.handleClick.bind(this);
}

现在成为

state = {isToggleOn: true};

最新更新