我不明白为什么this.click = this.click.bind(this)
是否需要以及它在做什么。
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
name: 'Initial State'
};
this.click = this.click.bind(this);
}
click() {
this.setState({
name: 'React Rocks!'
});
}
render() {
return (
<div>
<button onClick = {this.click}>Click Me</button>
<h1>{this.state.name}</h1>
</div>
);
}
};
If you didn't use bind()
, when this.click()
从事件监听器调用,其值this
would not是你的 React 组件(其中state
and props
等),但相反this
将是函数this.click()
本身。通常,每次调用函数时,执行上下文 - 的值this
- 设置为函数本身。
当然,如果您想访问 React 组件的上下文,这并不是一件好事。bind()
是确保函数在组件的相同执行上下文中运行的一种方法,使您可以访问this.state
, this.props
等你的函数内。另一种方法是使用 ES6 箭头函数声明:
let foo = () => {console.log("bar")}
它自动设置的值this
for foo
到函数声明的任何上下文。如果您声明foo
在与 React 组件相同的上下文中,它将保留该上下文,从而确保this
里面是一样的foo
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)