[英]React: Why do we not need to bind context to arrow functions being used as event listeners?
Looking at the react tutorial it explains that when we set event listeners, we generally have to bind the functions context, like is done here查看 react 教程,它解释说,当我们设置事件侦听器时,我们通常必须绑定函数上下文,就像在这里所做的那样
class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = {isToggleOn: true};
// This binding is necessary to make `this` work in the callback
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(state => ({
isToggleOn: !state.isToggleOn
}));
}
render() {
return (
<button onClick={this.handleClick}>
{this.state.isToggleOn ? 'ON' : 'OFF'}
</button>
);
}
}
I understand this, because unless we bind context to the this.handleClick
function we have no guarantee of what value this
will actually hold when we call this.setState
within the handleClick function.我理解这一点,因为除非我们将上下文绑定到
this.handleClick
function,否则当我们在 handleClick function 中调用this.setState
时,我们无法保证this
实际持有的值。 However, the tutorial goes on to state that we would not have to bind context to the handleClick function if we replaced <button onClick={this.handleClick}>
with <button onClick={() => this.handleClick}>
但是,教程继续到 state,如果我们将
<button onClick={this.handleClick}>
替换为<button onClick={() => this.handleClick}>
,我们将不必将上下文绑定到 handleClick function
How come the correct this
context is automatically bound when we use an arrow function?当我们使用箭头 function 时,如何自动绑定正确
this
上下文?
You don't need to but arrow functions keep context of this
as the object that defined them where traditional function context this
as the object that calls them.您不需要箭头函数将其上下文保留为
this
它们的 object,而传统的 function 上下文this
其保留为调用它们的 object。 You can use normal functions as long as they don't call this or keep a reference to this with a variable link const self = this
and use self instead of this.您可以使用普通函数,只要它们不调用 this 或通过变量链接
const self = this
保持对 this 的引用,并使用 self 而不是 this。
Why is this the case?为什么会这样? Because they designed it to be so.
因为他们设计的就是这样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.