我的反应组件中有一个文件mousemove事件,但是我无法访问我班级中的局部变量。我怎样才能做到这一点?
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.name = 'hello';
document.addEventListener ('mousemove', this.mousemoveListener, true);
}
mousemoveListener (e) {
console.log(this.name); // returns undefined
}
}
您需要绑定上下文:
this.mousemoveListener = this.mousemoveListener.bind(this)
在注册事件侦听器之前添加此行。
我建议你在JavaScript中了解this
的奇怪之处。
如果你想要Lexical范围,你可以使用箭头功能。这种方法的一个好帮手是你不必“记住”一直绑定“this”
你可以尝试改变
mousemoveListener (e) {
console.log(this.name); // returns undefined
}
对此
mousemoveListener = (e) => {
console.log(this.name);
}