使用NextJs获取滚动条位置



我使用NextJs来利用服务器端渲染。此外,我的应用程序中有一个导航栏,它应该随着滚动位置而改变样式。如何在我的NextJs应用程序上检查窗口是否滚动超过100px?

您可以简单地使用useEffect挂钩,如下所示:

import { useEffect, useState } from "react";
const IndexPage = () => {
const [scrollY, setScrollY] = useState(0);
useEffect(() => {
const handleScroll = () => {
setScrollY(window.scrollY);
};
// just trigger this so that the initial state 
// is updated as soon as the component is mounted
// related: https://stackoverflow.com/a/63408216
handleScroll();
window.addEventListener("scroll", handleScroll);
return () => {
window.removeEventListener("scroll", handleScroll);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return (
<div style={{ height: 4000 }}> {/* just added to make scrollbar available */}
<div style={{ position: "fixed", top: 0 }}>
{scrollY > 100
? "Scrolled more than 100px"
: "Still somewhere near the top!"}
</div>
</div>
);
};
export default IndexPage;

沙盒:https://codesandbox.io/s/cocky-drake-1xe0g

可以通过取消滚动处理程序来进一步优化此代码。可选的是,只有在状态没有更改的情况下才设置状态(不确定React的新版本是否自己处理(。

您的问题与此线程直接相关:https://stackoverflow.com/a/59403018/11613622

关于去抖动/节流,你可以参考:如何使用React Hook的节流或去抖动?

此外,如果您不想在该线程中使用所提供的解决方案,只需用_.debounce包装handleScroll,然后将其提供给事件处理程序。

最新更新