【问题标题】:Intersection Observer with React JS与 React JS 的交集观察者
【发布时间】:2022-01-20 15:01:12
【问题描述】:

我正在尝试使用React 监控带有IntersectionObserver 的页面部分。

有人可以帮助我实现这一点吗,我已经使用当前代码创建了一个代码沙箱。

https://codesandbox.io/s/eager-agnesi-virvq

【问题讨论】:

    标签: reactjs intersection-observer


    【解决方案1】:

    在您的Home.jsx 文件中。你没有在refs 上打电话给observeuseEffect 有不必要的依赖关系,导致无限循环。我已经修复了它们,现在您可以在日志中看到活动 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

    【讨论】:

    • @Ayodele,看看这个!!
    • @Amelia Senadherra 哇,谢谢,但希望我今天早些时候检查过,但我整天都在研究另一种方法,所以我想出了一个方法,但现在我在使用我的指示器导航到时遇到问题他们代表的部分,即平滑滚动到这些部分,我创建了一个沙箱,请问我该如何解决这个问题,你的方法也很好看,学到了一些东西,但现在我想为自己简化一些事情。这是我创建的代码沙箱codesandbox.io/s/upbeat-gould-qncl1?file=/src/App.js
    • 太好了!,您可以添加空依赖数组以避免在活动 id 更改时调用效果,并添加清除函数以在组件卸载时不观察 => codesandbox.io/s/red-haze-21tm4?file=/src/App.js
    • @Ayodele,通过改进更新了答案
    • @Amelia Senadheera 是的,我已经添加了对这个的依赖项,应该在我的代码框上对其进行编辑,但是我在使我的侧边栏可以单击圆圈并平滑滚动到视图中时遇到问题,你会得到什么我的意思是对吗?
    猜你喜欢
    • 2021-03-20
    • 1970-01-01
    • 2020-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-04
    • 1970-01-01
    相关资源
    最近更新 更多