首页 > 解决方案 > 当用户滚动反应功能组件时如何检测div标签区域?

问题描述

我需要这样的解决方案 [https://codepen.io/BraisC/pen/mxVwVm][1]

我想通过使用反应钩子使用反应功能组件来创建它。

标签: reactjs

解决方案


您可以添加事件侦听器以在 useEffect 上滚动,并在该回调中更新当前活动部分:

在这里检查我已经实现了这个

const [index, setIndex] = useState(0);

  useEffect(() => {
    window.addEventListener('scroll', handleScroll);

    return () => window.removeEventListener('scroll', handleScroll);
  }, []);

  const handleScroll = () => {
    if (window.pageYOffset <= 935 && index !== 0) {
      setIndex(0);
    } else if (
      window.pageYOffset > 935 &&
      window.pageYOffset <= 1870 &&
      index !== 1
    ) {
      setIndex(1);
    } else if (window.pageYOffset > 1870 && index !== 2) {
      setIndex(2);
    } else {
      setIndex(0);
    }
  };

  return (
    <div>
      <nav className="nav">
        <ul className="menu">
          <li
            className={index === 0 ? 'active' : ''}
            onClick={() => setIndex(0)}
          >
            <a href="#home">Home</a>
          </li>
          <li
            className={index === 1 ? 'active' : ''}
            onClick={() => setIndex(1)}
          >
            <a href="#main">Main</a>
          </li>
          <li
            className={index === 2 ? 'active' : ''}
            onClick={() => setIndex(2)}
          >
            <a href="#about">About</a>
          </li>
        </ul>
      </nav>
      <div id="home" className="section1 section" />
      <div id="main" className="section2 section" />
      <div id="about" className="section3 section" />
    </div>
  );

我会建议使用节流来限制触发的事件数量。


推荐阅读