javascript - 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.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
}
推荐阅读
- c# - 在 ASP.NET Core 上实现“一劳永逸”方法的安全方法
- identityserver4 - IdentityServer4:是否可以在运行时更改权限?
- sql - 在 Oracle SQL 中创建全局临时表
- bitwise-and - 按位和负整数不同于按位和正整数
- tomcat - Tomcat - 将数据库连接移出 server.xml
- java - 触发firebase功能后未弹出通知
- xquery - concat(fn:data(value),',') 连接 *all* 字符串,而不仅仅是 value
- android - 参数错误未定义
- mysql - MySQL 使用 like 匹配特定字符串
- jquery - 如何构建依赖于函数[jQuery]中生成的变量的动态ID点击函数?