是否可以在处理程序函数中删除并读取React eventListener



我正在使用类似于带有React的fullpage.js的东西,在转换过程中我需要删除eventListener。

有可能吗?

反应代码

function App() {
const wheelHandler = (event) => {
// I need to remove wheelHandler here
setTimeout(() => {
// I need to readd wheelHandler here
}, 1000); // Assume that the transition ends after 1000ms
};
return (
<div className="App" onWheel={wheelHandler} />
);
}

香草JS等效

const wheelHandler = (event) => {
window.removeEventListener(wheelHandler);
setTimeout(() => {
window.addEventListener(wheelHandler);
}, 1000);
};
window.addEventListener(wheelHandler);

附言:我在React上尝试了VanillaJS解决方案,但事件处理程序在单轮滚动上被触发了多次。因此,我别无选择,只能选择React的SyntheticEvent。

通过连接的方式,如果不使用一段状态,告诉您是否连接处理程序并重新渲染,这可能是杀鸡用牛刀。

相反,我会设置一个标志(可能通过ref在对象上(,告诉处理程序在您希望忽略调用的时间内忽略调用。

长长的东西:

function App() {
const {current: scrolling} = useRef({flag: false});
const wheelHandler = (event) => {
// I need to remove wheelHandler here
if (scrolling.flag) {
// Bail out
return;
}
scrolling.flag = true;
// ...other logic if any...
setTimeout(() => {
// I need to readd wheelHandler here
scrolling.flag = false;
}, 1000); // Assume that the transition ends after 1000ms
};
return (
<div className="App" onWheel={wheelHandler} />
);
}

或者你也可以这样做,你不需要额外的对象(我倾向于使用一个保存我所有非状态实例数据的引用,但你不必这样做(:

function App() {
const scrolling = useRef(false);
const wheelHandler = (event) => {
// I need to remove wheelHandler here
if (scrolling.current) {
// Bail out
return;
}
scrolling.current = true;
// ...other logic if any...
setTimeout(() => {
// I need to readd wheelHandler here
scrolling.current = false;
}, 1000); // Assume that the transition ends after 1000ms
};
return (
<div className="App" onWheel={wheelHandler} />
);
}

正如他们在useRef文档中所说,refs对于非状态实例信息很有用:

但是,useRef()的作用远不止于ref属性。它可以方便地保持任何可变值,类似于在类中使用实例字段的方式。

最新更新