mos*_*awn 3 javascript addeventlistener lodash reactjs react-hooks
我正在尝试使用我的React应用程序的lodash库限制滚动事件“滚轮”,但没有成功。
我需要从滚动输入中监听e.deltaY以便检测其滚动方向。为了添加一个侦听器,我编写了一个React钩子,该钩子接受一个事件名和一个处理函数。
基本实施
const [count, setCount] = useState(0);
const handleSections = () => {
setCount(count + 1);
};
const handleWheel = _.throttle(e => {
handleSections();
}, 10000);
useEventListener("wheel", handleWheel);
Run Code Online (Sandbox Code Playgroud)
我的useEventListener挂钩
function useEventListener(e, handler, passive = false) {
useEffect(() => {
window.addEventListener(e, handler, passive);
return function remove() {
window.removeEventListener(e, handler);
};
});
}
Run Code Online (Sandbox Code Playgroud)
工作演示:https : //codesandbox.io/s/throttledemo-hkf7n
我的目标是限制此滚动事件,以减少触发的事件,并有几秒钟的时间以编程方式滚动我的页面(scrollBy(),示例)。目前,节流似乎不起作用,所以我一次收到了很多滚动事件
当您可以调用_.throttle()一个函数时,您将获得一个新的函数,可以“管理”原始函数的调用。每当调用包装器函数时,包装器都会检查是否经过了足够的时间,如果有足够的时间,它将检查原始函数。
如果_.throttle()多次调用,它将返回一个没有调用该函数的“历史记录”的新函数。然后它将一次又一次地调用原始函数。
在您的情况下,包装函数在每个渲染器上重新生成。_.throttle()使用useCallback(沙盒)将呼叫包裹:
const { useState, useCallback, useEffect } = React;
function useEventListener(e, handler, cleanup, passive = false) {
useEffect(() => {
window.addEventListener(e, handler, passive);
return function remove() {
cleanup && cleanup(); // optional specific cleanup for the handler
window.removeEventListener(e, handler);
};
}, [e, handler, passive]);
}
const App = () => {
const [count, setCount] = useState(0);
const handleWheel = useCallback(_.throttle(() => {
setCount(count => count + 1);
}, 10000, { leading: false }), [setCount]);
useEventListener("wheel", handleWheel, handleWheel.cancel); // add cleanup to cancel throttled calls
return (
<div className="App">
<h1>Event fired {count} times</h1>
<h2>It should add +1 to cout once per 10 seconds, doesn't it?</h2>
</div>
);
};
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);Run Code Online (Sandbox Code Playgroud)
.App {
font-family: sans-serif;
text-align: center;
}Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root"></div>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
173 次 |
| 最近记录: |