如何从文档事件中获取对组件做出反应的引用?

问题描述 投票:2回答:2

我的反应组件中有一个文件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
        }
}
javascript reactjs
2个回答
2
投票

您需要绑定上下文:

this.mousemoveListener = this.mousemoveListener.bind(this)

在注册事件侦听器之前添加此行。

我建议你在JavaScript中了解this的奇怪之处。


2
投票

如果你想要Lexical范围,你可以使用箭头功能。这种方法的一个好帮手是你不必“记住”一直绑定“this”

你可以尝试改变

    mousemoveListener (e) {
        console.log(this.name); // returns undefined
    }

对此

    mousemoveListener = (e) => {
        console.log(this.name);
    }
© www.soinside.com 2019 - 2024. All rights reserved.