释放鼠标时,mousemove
似乎没有正确删除。document
问问题
355 次
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);
于 2019-10-14T14:22:15.620 回答