简体   繁体   English

ReactJS。 如何在创建的侦听器中删除事件侦听器?

[英]ReactJS. How to remove event listener inside created listener?

onDragEnd event listens for touchend or mouseup . onDragEnd事件监听touchendmouseup If onDragEnd function is triggered then touchmove and mousemove should be removed, but it does not work.如果onDragEnd function 被触发然后touchmovemousemove应该被删除,但它不起作用。 How to correctly remove mousemove or touchmove events after touchend or mouseup is called?如何在touchendmouseup后正确删除mousemovetouchmove事件?

Source:资源:

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);
    };
  }, []);

You need to pass the same reference of the function to removeEventListener that you used to addEventListener .您需要将 function 的相同引用传递给您用于addEventListenerremoveEventListener

Now since your functions are within functional component and may set state, new reference of the functions are created and hence events are not properly removed.现在,由于您的函数在函数组件中并且可以设置 state,因此会创建函数的新引用,因此不会正确删除事件。

You can make use of useCallback to memoize the function references which will help in removing the events您可以使用 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM