侧边屏幕滚动导航
时间: 2023-07-18 22:21:51 浏览: 61
好的,下面是使用React实现侧边屏幕滚动导航的代码示例:
```jsx
import React, { useState } from "react";
const SideNav = ({ sections }) => {
const [activeSection, setActiveSection] = useState(0);
const handleScroll = () => {
const currentScrollPos = window.pageYOffset;
const sectionOffsets = sections.map((section) => {
const element = document.getElementById(section.id);
return {
id: section.id,
offset: element.offsetTop,
height: element.offsetHeight,
};
});
const activeSection = sectionOffsets.reduce((prev, curr) => {
if (curr.offset - 200 <= currentScrollPos) {
return curr.offset > prev.offset ? curr : prev;
}
return prev;
}, sectionOffsets[0]);
setActiveSection(activeSection.id);
};
window.addEventListener("scroll", handleScroll);
return (
<ul>
{sections.map((section) => (
<li
key={section.id}
className={activeSection === section.id ? "active" : ""}
>
<a href={`#${section.id}`}>{section.title}</a>
</li>
))}
</ul>
);
};
export default SideNav;
```
上述代码中,我们使用了React的useState钩子来管理当前活跃的部分的状态。在handleScroll函数中,我们获取每个部分的偏移量和高度,并将其存储在sectionOffsets数组中。然后,我们使用reduce方法来查找当前滚动位置下的活动部分。最后,我们将活动部分的ID存储在状态变量activeSection中,并在渲染时使用它来确定哪个部分应该被激活。
这是一个基本的示例,你可以根据自己的需要进行修改和扩展。希望对你有所帮助!