使用 NextJs 获取滚动条位置
Get scrollbar position with NextJs
我正在使用 NextJs 来利用服务器端渲染。而且我的应用程序中有一个导航栏,它应该随着滚动位置改变样式。在我的 NextJs 应用程序中,如何检查 window 是否已滚动超过 100 像素?
您可以像这样简单地使用 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:
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 是否会自行处理)。
您的问题与此主题直接相关:
对于debouncing/throttling你可以参考这个:
此外,如果您不想在该线程中使用提供的解决方案,只需将 handleScroll
包裹在 _.debounce
中,然后将其提供给事件处理程序。
我正在使用 NextJs 来利用服务器端渲染。而且我的应用程序中有一个导航栏,它应该随着滚动位置改变样式。在我的 NextJs 应用程序中,如何检查 window 是否已滚动超过 100 像素?
您可以像这样简单地使用 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:
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 是否会自行处理)。
您的问题与此主题直接相关:
对于debouncing/throttling你可以参考这个:
此外,如果您不想在该线程中使用提供的解决方案,只需将 handleScroll
包裹在 _.debounce
中,然后将其提供给事件处理程序。