gpt4 book ai didi

javascript - React 无法触发 window.onmouseup

转载 作者:行者123 更新时间:2023-11-28 03:08:45 24 4
gpt4 key购买 nike

我有一个 slider 组件,它应该在鼠标抬起后停止移动。我浏览过论坛,我的代码与 here 非常相似

const Slider = ({ mainColour }) => {
const [cursorPos, setCursorPos] = React.useState(0);
const [isSliding, setSliding] = React.useState(false);
const ref = React.useRef();

const drag = e => {
console.log("dragging");
setCursorPos(e.pageY);
};

const startDrag = e => {
setSliding(true);
window.addEventListener("mousemove", drag);
window.addEventListener("mouseup", function() {
ref.current.onmousedown = null;
ref.current.onmouseup = null;
ref.current.onmousemove = null;
setSliding(false);
window.onmouseup = null;
});
};

return (
<div
className={`cursor ${isSliding ? "active" : ""}`}
ref={ref}
style={{
top: `${cursorPos}px`,
backgroundColor: `${mainColour}`
}}
onMouseDown={event => startDrag(event)}
></div>
);
};

export default Slider;

但是,当 startDrag 触发时,window.onmouseup 监听器似乎不起作用,并且不会停止 slider 。对于为什么它不起作用的任何见解,我们将不胜感激。

最佳答案

<强> https://codesandbox.io/s/lucid-sunset-8e78r

React 可以触发 mouseup,只需在 mouseup 时使用 window.removeEventListener 进行 drag() >。这就是为什么您在 mouseup 之后在控制台中看到 dragging 的原因,您只是忘记取消订阅该事件:)

window.onmouseup = null;window.removeEventListener("mousemove") 不同。

const Slider = ({ mainColour }) => {
const [cursorPos, setCursorPos] = React.useState(0);
const [isSliding, setSliding] = React.useState(false);
const ref = React.useRef();

const drag = e => {
console.log("dragging");
setCursorPos(e.pageY);
};

useEffect(() => {
if (isSliding) {
window.addEventListener("mousemove", drag);
}
}, [isSliding]);

useEffect(() => {
window.addEventListener("mouseup", function() {
window.removeEventListener("mousemove", drag);
setSliding(false);
});
});

const startDrag = () => setSliding(true);

return (
<div
className={`cursor ${isSliding ? "active" : ""}`}
ref={ref}
style={{
top: `${cursorPos}px`,
backgroundColor: `${mainColour}`
}}
onMouseDown={event => startDrag(event)}
/>
);
};

关于javascript - React 无法触发 window.onmouseup,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60355100/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com