【发布时间】:2022-07-05 17:10:29
【问题描述】:
我在尝试控制 scroll 和 wheel 事件时遇到问题。
目前,我可以通过将事件侦听器添加到 window 对象来阻止这些特定事件,但它们的处理程序需要停用 passive 才能工作。这在尝试删除它们时会导致问题,因为“删除”事件处理程序上似乎不存在passive,并且浏览器似乎没有删除正确的事件处理程序。 Here's a link to a reproducible example 以及我在下面使用的钩子的代码
有人对此有什么好的解决方案或解决方法吗?大多数相关问题似乎没有很好(或当前)的答案来处理最近的浏览器更新以允许被动事件
const useControlScrolling = (pauseScroll: boolean): void => {
useEffect(() => {
const preventScroll = (e: Event) => {
e.preventDefault();
};
const eventOpts = {
passive: false
};
const disableScrolling = () => {
console.log("disabling scroll");
// I add the passive prop to the allow `preventDefault` to work
window.addEventListener("wheel", preventScroll, eventOpts);
window.addEventListener("scroll", preventScroll, eventOpts);
};
const enableScrolling = () => {
console.log("enabling scroll");
// the remove handler doesn't allow the eventOpts so it doesn't know which handler to remove. Casting it does not help
window.removeEventListener("wheel", preventScroll);
window.removeEventListener("scroll", preventScroll);
};
if (pauseScroll) {
disableScrolling();
} else {
enableScrolling();
}
}, [pauseScroll]);
};
export default function App() {
const [visible, setVisible] = useState(false);
useControlScroll(visible);
window.addEventListener("click", () => setVisible(!visible));
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
【问题讨论】:
标签: reactjs typescript events