繁体   English   中英

React:为什么一定要绑定这个方法?

[英]React: why do you have to bind this method?

我正在阅读这篇关于 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}行中使用。 即使我们没有进行绑定,这也不会起作用吗?

this里面handleChange要提到的方法和不将组件实例( Calculator )。 由于handleChange没有setState方法(组件有),我们必须在方法中绑定正确的this 如果您有另一种没有对this做任何事情的方法,那么是的,您可以跳过绑定。

来自官方文档:

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

规避此问题的一种方法是使用粗箭头语法(如 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
}

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

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM