我正在尝试创建具有粘性效果的标题,但是在滚动页面时遇到此错误,有时有效,有时会发生错误。谁能帮我解决这个问题吗?
const EventPage: React.FC = () => {
const [isSticky, setSticky] = useState(false);
const ref = useRef(null);
const handleScroll = () => {
if (ref.current.getBoundingClientRect().y <= -580 || null) {
console.log(ref.current.getBoundingClientRect().y);
setSticky(true);
} else {
setSticky(false);
}
};
useEffect(() => {
window.addEventListener("scroll", handleScroll);
return () => {
window.removeEventListener("scroll", () => handleScroll);
};
}, []);
return (
<div>
<Head>
<title>Event Page</title>
</Head>
<Header />
<div className={`sticky-wrapper${isSticky ? " sticky" : ""}`} ref={ref}>
{isSticky && <Sticky />}
</div>
Run Code Online (Sandbox Code Playgroud)
refs 在重新渲染时可以为 null,因此在访问元素 refs 的属性之前始终进行 null 检查。以下是盖伦对裁判的评价。
const handleScroll = () => {
if(!ref.current) return
if (ref.current.getBoundingClientRect().y <= -580 || null) {
console.log(ref.current.getBoundingClientRect().y);
setSticky(true);
} else {
setSticky(false);
}
};Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
44233 次 |
| 最近记录: |