【发布时间】: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