[英]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.