首页 > 解决方案 > React:为什么要绑定这个方法?

问题描述

我正在阅读这篇关于 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.handleChangethis. 它在线路中使用onChange={this.handleChange}。即使我们没有进行绑定,这不也一样吗?

标签: javascriptreactjsbinding

解决方案


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

来自官方文档:

如果您需要在处理程序中访问父组件,您还需要将函数绑定到组件实例。

避免这种情况的一种方法是使用胖箭头语法(如 Dimitar 的回答)或使用React Hook API


换句话说(见评论):

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
}

推荐阅读