我正在尝试制作一个可拖动的React组件,代码总是能够达到“移除监听器”模块,但之后组件仍然会继续粘在我的鼠标上,所以显然我搞砸了移除监听器的步骤,不过我不确定具体是哪里错了——我传递给document.add/removeEventListener的两个函数肯定是相同的吧?
useEffect(() => {
if (dragging && !prevDragging) {
document.addEventListener("mousemove", onMouseMove)
document.addEventListener("mouseup", onMouseUp)
} else if (!dragging && prevDragging) {
console.log('removing listeners')
document.removeEventListener("mousemove", onMouseMove)
document.removeEventListener("mouseup", onMouseUp)
}
}
)
const onMouseMove = (e) => {
if (!dragging) return;
setPos({
x: e.pageX - rel.x,
y: e.pageY - rel.y
});
e.stopPropagation();
e.preventDefault();
}
const onMouseUp = (e) => {
setDragging(false);
e.stopPropagation();
e.preventDefault();
}