【发布时间】:2022-01-20 15:01:12
【问题描述】:
我正在尝试使用React 监控带有IntersectionObserver 的页面部分。
有人可以帮助我实现这一点吗,我已经使用当前代码创建了一个代码沙箱。
【问题讨论】:
标签: reactjs intersection-observer
我正在尝试使用React 监控带有IntersectionObserver 的页面部分。
有人可以帮助我实现这一点吗,我已经使用当前代码创建了一个代码沙箱。
【问题讨论】:
标签: reactjs intersection-observer
在您的Home.jsx 文件中。你没有在refs 上打电话给observe。 useEffect 有不必要的依赖关系,导致无限循环。我已经修复了它们,现在您可以在日志中看到活动 ID。
当组件被挂载时,在清理函数中对每个ref 调用unobserve。 (这对于避免内存泄漏很重要)
useEffect(() => {
const observer = new IntersectionObserver(
(entries) => {
for (let entry of entries) {
// if 90% of the section is visible
if (entry.isIntersecting) {
// update the active state to the visible section
setActive(entry.target.id);
}
}
},
{
// root property defaults to the browser viewport
// intersection ratio (90% of section must be visibile)
threshold: 0.9
}
);
refs.forEach((ref) =>
// observe the refs that were applied to the sections
observer.observe(ref.current)
);
// cleanup function
return () => {
refs.forEach((ref) => ref.current && observer.unobserve(ref.current));
};
}, []);
代码沙箱 => https://codesandbox.io/s/red-haze-21tm4?file=/src/App.js
【讨论】: