reactjs - 当用户滚动反应功能组件时如何检测div标签区域?
问题描述
我需要这样的解决方案 [https://codepen.io/BraisC/pen/mxVwVm][1]
我想通过使用反应钩子使用反应功能组件来创建它。
解决方案
您可以添加事件侦听器以在 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>
);
我会建议使用节流来限制触发的事件数量。
推荐阅读
- java - 如何在 Java 中测试不同的“表格输入”?
- typescript - 按聚合列排序
- windows - 安装appx bundle时如何禁用Launch when ready复选框?
- jquery - TypeError: $.ajax 不是 HTMLSelectElement 的函数
- reactjs - TypeError:无法读取 reactjs 中未定义的属性“toLowerCase”
- python - 请求加入 Google Meet Selenium
- r - 如何用 R 读取季度数据?
- python - 在外部 python 包中使用主线程的默认 event_loop 是一种好习惯吗?
- r - 如何在 R Facebook Prophet 中进行月度预测,数据也是月度
- sql - 转 SQL 查询,其中包含多个联接、左联接、分组依据和必须到 EF 核心