[英]Add and Remove event listeners in React with componentDidMount and componentWillUnmount
componentDidMount() {
document.addEventListener('mousemove', (e) => this.customCursorFollow(e));
document.addEventListener('click', this.customCursorClick);
}
componentWillUnmount() {
document.removeEventListener('mousemove', (e) =>
this.customCursorFollow(e)
);
document.removeEventListener('click', this.customCursorClick);
}
customCursorFollow(e) {
const cursor = document.querySelector('.cursor');
cursor.setAttribute(
'style',
'top: ' + (e.pageY - 20) + 'px; left: ' + (e.pageX - 20) + 'px;'
);
}
customCursorClick() {
const cursor = document.querySelector('.cursor');
cursor.classList.add('expand');
setTimeout(() => {
cursor.classList.remove('expand');
}, 500);
}
in React my addEvent listener and remove event listener aren't working properly.在 React 中,我的 addEvent 侦听器和删除事件侦听器无法正常工作。 Specifically, the removeEventListener is not working for the customCursorFollow.
具体来说,removeEventListener 不适用于 customCursorFollow。
ALSO: Is this the best way to add event and remove event listeners in React?还:这是在 React 中添加事件和删除事件侦听器的最佳方式吗? with componentDidMount and componentWillUnmount?
使用 componentDidMount 和 componentWillUnmount?
With addEventListener
and removeEventListener
, one major requirement is that the function reference passed to addEventListener
should be the same the one passed to removeEventListener
.对于
addEventListener
和removeEventListener
,一个主要要求是传递给addEventListener
的 function 引用应该与传递给removeEventListener
的引用相同。
Now when you use arrow functions the reference differs and hence the listener is not removed correctly.现在,当您使用箭头函数时,引用会有所不同,因此无法正确删除侦听器。
Since you just need event to be passed you don't need a listener to be an arrow function.由于您只需要传递事件,因此您不需要将侦听器作为箭头 function。
componentDidMount() {
document.addEventListener('mousemove', this.customCursorFollow);
document.addEventListener('click', this.customCursorClick);
}
componentWillUnmount() {
document.removeEventListener('mousemove', this.customCursorFollow);
document.removeEventListener('click', this.customCursorClick);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.