gpt4 book ai didi

javascript - 如何从文档事件中获取对 react 组件的引用?

转载 作者:行者123 更新时间:2023-11-29 17:46:26 25 4
gpt4 key购买 nike

我的 React 组件中有一个文档 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
}
}

最佳答案

您需要绑定(bind)上下文:

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

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

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

关于javascript - 如何从文档事件中获取对 react 组件的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49075889/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com