[英]ReactJS. How to remove event listener inside created listener?
onDragEnd
事件监听touchend
或mouseup
。 如果onDragEnd
function 被触发然后touchmove
和mousemove
应该被删除,但它不起作用。 如何在touchend
或mouseup
后正确删除mousemove
或touchmove
事件?
资源:
const onDragEnd = () => {
window.removeEventListener('touchmove', handleTouchMove);
window.removeEventListener('mousemove', handleMouseMove);
setIsDragging(false);
setTranslate(0);
};
const handleMouseDown = event => {
onDragStart(event.clientX);
window.addEventListener('mousemove', handleMouseMove);
};
const handleTouchStart = event => {
const touch = event.targetTouches[0];
onDragStart(touch.clientX);
window.addEventListener('touchmove', handleTouchMove);
};
useEffect(() => {
window.addEventListener('touchend', onDragEnd);
window.addEventListener('mouseup', onDragEnd);
return () => {
window.removeEventListener('touchend', onDragEnd);
window.removeEventListener('mouseup', onDragEnd);
};
}, []);
您需要将 function 的相同引用传递给您用于addEventListener
的removeEventListener
。
现在,由于您的函数在函数组件中并且可以设置 state,因此会创建函数的新引用,因此不会正确删除事件。
您可以使用 useCallback 来记忆 function 参考,这将有助于删除事件
const handleTouchMove = useCallback(() => {
}, []);
const handleMouseMove = useCallback(() => {
}, [])
const onDragEnd = useCallback(() => {
window.removeEventListener('touchmove', handleTouchMove);
window.removeEventListener('mousemove', handleMouseMove);
setIsDragging(false);
setTranslate(0);
}, []);
const handleMouseDown = useCallback(event => {
onDragStart(event.clientX);
window.addEventListener('mousemove', handleMouseMove);
}, []);
const handleTouchStart = useCallback(event => {
const touch = event.targetTouches[0];
onDragStart(touch.clientX);
window.addEventListener('touchmove', handleTouchMove);
}, []);
useEffect(() => {
window.addEventListener('touchend', onDragEnd);
window.addEventListener('mouseup', onDragEnd);
return () => {
window.removeEventListener('touchend', onDragEnd);
window.removeEventListener('mouseup', onDragEnd);
};
}, []);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.