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



我的反应组件中有一个文档鼠标移动事件,但我无法访问类中的局部变量。我该怎么做?

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的奇怪之处。

如果你想要词法范围,你可以使用箭头函数。这种方法的一个很好的优点是,您不必一直"记住"绑定"这个">

您可以尝试更改

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

对此

    mousemoveListener = (e) => {
        console.log(this.name);
    }

最新更新