0

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

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

4

1 回答 1

0

与其在相关时手动添加和删除,不如编写一个自定义挂钩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

于 2019-10-14T14:22:15.620 回答