提问人:Uday 提问时间:11/5/2023 最后编辑:Mike DoeUday 更新时间:11/6/2023 访问量:64
JS 滚动事件在 React 的 useEffect 中没有触发
JS scroll event is not trigerring inside React's useEffect
问:
我想在我的网站上添加无限滚动功能,但是我在滚动页面时遇到了滚动事件监听器的问题,该问题没有触发。
useEffect(() => {
window.addEventListener("scroll", handleInfiniteScrolling);
console.log("Hello");
return () => {
window.removeEventListener("scroll", handleInfiniteScrolling);
};
}, []);
const handleInfiniteScrolling = async () => {
try {
console.log("Scroll Height", document.documentElement.scrollHeight);
console.log("Inner Height", window.innerHeight);
console.log("scrollTop", document.documentElement.scrollTop);
} catch (err) {
console.log(err);
}
};
return (
<>
<div
className="results-page"
style={{
height: "100vh",
overflow: 'scroll',
}}
>
{data.map((item) => (
<MainLayer props={item} key={item._id} />
))}
</div>
</>
);
答:
2赞
Ori Drori
11/6/2023
#1
是滚动容器,其中的内容是滚动的。您需要将事件侦听器添加到 using the event:div
div
div
onScroll
const data = Array.from({ length: 100 }, () => ({ _id: crypto.randomUUID() }));
const Demo = () => {
const handleInfiniteScrolling = e => {
console.log(e.target.scrollTop)
};
return (
<div
onScroll={handleInfiniteScrolling}
className="results-page"
style={{
height: "100vh",
overflow: 'scroll',
}}
>
{data.map(item => (
<div key={item._id}>{item._id}</div>
))}
</div>
);
};
ReactDOM
.createRoot(root)
.render(<Demo />);
html, body {
margin: 0;
}
<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
<div id="root"></div>
评论