我为 Hooks 尝试了这个问题 Update style of a component onScroll in React.js 的解决方案
import React, { useEffect, useState } from 'react';
function MyApp () {
const [offset, setOffset] = useState(0);
useEffect(() => {
window.onscroll = () => {
setOffset(window.pageYOffset)
}
}, []);
console.log(offset);
};
我收到错误 Error: Too many re-renders. React limits the number of renders to prevent an infinite loop
。我阅读了需要添加清理的评论。所以我使用 addEventListener
useEffect(() => {
window.addEventListener('scroll', handleScroll);
return function cleanup () {
window.removeEventListener('scroll', handleScroll);
};
}, []);
const handleScroll = () => {
setOffset(window.pageYOffset)
}
我已经清理了 useEffect 但仍然出现错误。问题不在于清理,而在于 handleScroll
中的 setState编辑: 我刚刚为我的问题找到了解决方案,呵呵。但是我遇到了一个新问题。我无法访问 useEffect 内部的高度,因此它始终为 0
const [height, setHeight] = useState(0);
const ref = useRef(null);
const [isNavbarSticky, setIsNavbarSticky] = useState(false);
useEffect(() => {
const handleScroll = () => {
const position = window.pageYOffset;
if (position > height) {
setIsNavbarSticky(!isNavbarSticky);
}
if (position < height) {
setIsNavbarSticky(!isNavbarSticky);
}
}
window.addEventListener('scroll', handleScroll);
return function cleanup () {
window.removeEventListener('scroll', handleScroll);
};
}, [window.pageYOffset]);
useEffect(() => {
setHeight(ref.current.clientHeight);
}, []);