【问题标题】:Problem highlighting sidebar navigation items on scroll in React with IntersectionObserver使用 IntersectionObserver 在 React 中滚动时突出显示侧边栏导航项的问题
【发布时间】:2021-06-24 19:47:50
【问题描述】:

我正在处理一个反应项目,我想在滚动时显示相应部分时突出显示侧边栏导航列表,为此我使用了 useEffect 和 IntersectionObserver 并使用代码向侧边栏导航项添加了一个活动类下面。

问题是某些部分不是视口的 100% 高度,导致多个侧边栏导航列表项同时突出显示,我不希望这样。我只希望一个导航项具有活动类。

 useEffect(() => {
    const observer = new IntersectionObserver((entries) => {
      entries.forEach((entry) => {
        const id = entry.target.getAttribute('id');

        if (entry.isIntersecting) {
          document
            .querySelector(`.sidebarList li a[href="#${id}"]`)
            .classList.add('active');
        } else {
          document
            .querySelector(`.sidebarList li a[href="#${id}"]`)
            .classList.remove('active');
        }
      });
    });

    document.querySelectorAll('section[id]').forEach((section) => {
      observer.observe(section);
    });

    return () => observer.disconnect();
   });

【问题讨论】:

    标签: javascript reactjs intersection-observer


    【解决方案1】:

    我认为您将不得不使用 useRef 而不是使用您的 querySelector。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-19
      • 1970-01-01
      相关资源
      最近更新 更多