【问题标题】:Why we have to bind a method in Class Component React为什么我们必须在类组件 React 中绑定一个方法
【发布时间】:2022-06-15 16:29:16
【问题描述】:

我一直在阅读文档并练习 React 文档中的一些东西,直到我最终进入事件处理部分。但我不明白为什么在类组件中使用方法时我们必须绑定函数,谁能解释一下?例如:

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

【问题讨论】:

  • this 绑定到this.handleClick - 因为没有它,事件处理程序中的this 将是click 发生的元素

标签: javascript reactjs


猜你喜欢
  • 2021-12-02
  • 2017-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-03
  • 1970-01-01
  • 2012-01-26
  • 2012-04-04
相关资源
最近更新 更多