【发布时间】:2016-11-09 01:07:34
【问题描述】:
了解handling events in React,其他人可以在以下两种情况下如何绑定吗?如果可以引用handleClick 和this.handleClick,为什么还需要绑定呢?处理程序内部的this 不会已经指向组件,因为它是调用处理程序的组件吗?另外,为什么将处理程序放在匿名函数中也可以?
在 JSX 回调中你必须小心 this 的含义。在 JavaScript,类方法默认不绑定。如果你忘记 绑定 this.handleClick 并将其传递给 onClick,这将是未定义的 当函数被实际调用时。
解决办法是这样的:
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);
}
但是为什么这也有效呢?
class LoggingButton extends React.Component {
handleClick() {
console.log('this is:', this);
}
render() {
// This syntax ensures `this` is bound within handleClick
return (
<button onClick={(e) => this.handleClick(e)}>
Click me
</button>
);
}
}
【问题讨论】:
-
我建议阅读有关
this工作原理的更详细说明:github.com/getify/You-Dont-Know-JS/blob/…。那么应该就清楚了。
标签: javascript reactjs ecmascript-6