【问题标题】:React: why do you have to bind this method?React:为什么要绑定这个方法?
【发布时间】:2020-06-06 01:33:30
【问题描述】:

我正在阅读 this article 在 React 中的“提升状态”。它定义Calculator组件如下:

class Calculator extends React.Component {
  constructor(props) {
    super(props);
    this.handleChange = this.handleChange.bind(this);
    this.state = {temperature: ''};
  }

  handleChange(e) {
    this.setState({temperature: e.target.value});
  }

  render() {
    const temperature = this.state.temperature;
    return (
      <fieldset>
        <legend>Enter temperature in Celsius:</legend>
        <input
          value={temperature}
          onChange={this.handleChange} />

        <BoilingVerdict
          celsius={parseFloat(temperature)} />

      </fieldset>
    );
  }
}

this.handleChange = this.handleChange.bind(this); 行中,我想知道为什么我们必须将this.handleChange 绑定到this。它在onChange={this.handleChange} 行中使用。即使我们没有进行绑定,这不也一样吗?

【问题讨论】:

  • handleChange 中的 this 将引用方法而不是组件实例 (Calculator)。由于handleChange 没有setState 方法(组件有),我们必须在方法中绑定正确的this。如果您有另一种方法对 this 没有执行任何操作,那么可以,您可以跳过绑定。
  • 完美,谢谢。想把这个作为答案吗?

标签: javascript reactjs binding


【解决方案1】:

handleChange 中的 this 将引用方法而不是组件实例 (Calculator)。由于handleChange 没有setState 方法(组件有),我们必须在方法中绑定正确的this。如果您有另一种方法对 this 没有任何作用,那么是的,您可以跳过绑定。

来自官方文档:

如果需要在handler中访问父组件,还需要将函数绑定到组件实例上。

避免这种情况的一种方法是使用fat arrow syntax(如Dimitar 的回答)或使用React Hook API


换句话说(见 cmets):

constructor(props) {
  super(props);
  this.state = {temperature: ''};
}

handleChange(e) {
  this.setState({temperature: e.target.value});
  // ^ this = handleChange. You cannot call setState on handleChange.
}


constructor(props) {
  super(props);
  this.handleChange = this.handleChange.bind(this);
  this.state = {temperature: ''};
}

handleChange(e) {
  this.setState({temperature: e.target.value});
  // ^ this = Calculator component. All React (class) Components have setState
}

【讨论】:

    【解决方案2】:

    这与作用域有关,是 ES6 通过实现胖箭头函数解决的问题。

    基本上,当您在 JavaScript 中的类中创建方法时,该方法不会立即继承 this,因此任何对 this 的引用都会导致错误。为了解决这个问题,您需要将函数绑定到this,这实际上将类的一个实例作为参数传递给函数(如果您在后台查看)。

    如果你想避免这种绑定,你可以像这样使用一个粗箭头函数:

    handleChange = e => this.setState({[e.target.name]: e.target.value})
    

    在那个基本示例中,我在没有将方法绑定到 this 的情况下引用了 this 并且没有收到错误,因为胖箭头函数自动绑定到 this

    【讨论】:

    • 这太好了,谢谢!我在上面告诉克里斯,我会批准他的回答,因为他先到了那里,但是您关于箭头函数的 cmets 增加了一些我需要的额外见解。
    • 我个人不关心声誉,但一般来说,您会为下一个可能需要帮助的人批准最准确或最佳的答案。
    • 你的答案都是准确的。我不会说一个比另一个更准确。这就是为什么我选择批准他但同时赞成两者。
    猜你喜欢
    • 2012-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-28
    相关资源
    最近更新 更多