了解handling events in React,可以有人如何绑定在两种情况下工作?如果您可以使用this.handleClick
参考,为什么还需要绑定它?处理程序中的this
不会指向组件,因为它是调用处理程序的组件?另外,为什么将处理程序放在一个匿名函数中也可以工作?如何将事件处理程序放入React修补程序中的匿名函数中绑定问题?
你必须在JSX回调中小心这个含义。在 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'工作的更广泛的解释:https://github.com/getify/You-Dont-Know-JS/blob/71be65de0f5de05336ec97cd33e704a9b6074663/this%20%26%20object% 20原型/ README.md。那么它应该清楚。 –