我正在阅读这篇关于 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
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句