如何在拖动 React 组件的上下文中删除事件监听器

How to remove a event listener in the context of dragging a React component

释放鼠标时,mousemove 似乎没有从 document 中正确删除。

https://codesandbox.io/s/dragondrop-dqs46

与其手动添加和删除 相关,不如编写自定义挂钩 useEvent 将处理程序从一个渲染存储到另一个渲染:

useEvent.js

import { useEffect, useRef } from "react";

export default function(event, handler, element=window) {

  const savedHandler = useRef();

  useEffect(() => {
    savedHandler.current = handler;
  }, [handler]);

  useEffect(() => {
    const eventListener = event => savedHandler.current(event);
    element.addEventListener(event, eventListener);
    return () => element.removeEventListener(event, eventListener);
  }, [event, element]);
}

components/Dragon.js

useEvent("mousemove", onDrag);
useEvent("mouseup", onDragEnd);

工作笔:https://codesandbox.io/s/dragondrop-ceocx