这里是React钩子。我想模仿这个网站上的行为:Humboldt forum
基本上,导航栏是粘性的,向下滚动时隐藏,快速向上滚动时重新出现,总是在顶部可见。
const useScrollSpeed = (navHeight: number, maxScrollSpeed: number) => {
const [lastScrollTime, setLastScrollTime] = useState(new Date().getTime());
const [currentScrollPos, setCurrentScrollPos] = useState(0)
const [prevScrollPos, setPrevScrollPos] = useState(0);
const [visible, setVisible] = useState(true);
const handleScroll = () => {
const distance = Math.abs(currentScrollPos - prevScrollPos);
const scrollSpeed = distance / (new Date().getTime() - lastScrollTime);
if (currentScrollPos > prevScrollPos) {
setVisible(false);
} else {
if (scrollSpeed > maxScrollSpeed) {
setVisible(true);
}
}
setPrevScrollPos(currentScrollPos);
setLastScrollTime(new Date().getTime());
};
if (typeof window !== "undefined") {
useEffect(() => {
setCurrentScrollPos(window.scrollY)
if (currentScrollPos < navHeight) {
setVisible(true);
}
window.addEventListener("scroll", handleScroll);
return () => window.removeEventListener("scroll", handleScroll);
}, [window.scrollY]);
}
return visible;
};
export default useScrollSpeed;
我如何进一步优化它以提高性能?
1条答案
按热度按时间3htmauhk1#
以下是我的ES-Linted版本: