我正在用盖茨比( gatsby )构建一个投资组合网站,在那里我在左边有一个边栏,有一些链接(Home,about,work,等等)。右边是主要的内容,是一个很长的部分。单击链接只会滚动到该部分。我希望当用户到达该部分时,链接的样式会有所不同。我在中找到了一个解决方案,可以应用活动状态,但我不知道如何以反应的方式来实现这一点。
useEffect(() => {
const navbarlinks = document.querySelectorAll("nav a");
const navbarlinksActive = () => {
let position = window.scrollY + 200;
navbarlinks.forEach((navbarlink) => {
let section = document.querySelector(navbarlink.hash);
if (position >= section.offsetTop && position <= section.offsetTop + section.offsetHeight) {
navbarlink.classList.add("active");
} else {
navbarlink.classList.remove("active");
}
});
};
window.addEventListener("load", navbarlinksActive);
document.addEventListener("scroll", navbarlinksActive);
return () => {
window.removeEventListener("load", navbarlinksActive);
document.removeEventListener("scroll", navbarlinksActive);
};
}, []);我选择所有的导航链接,然后循环它们,得到哈希属性,这将匹配相应部分的id,然后被选中。然后根据类的位置添加或删除类。此代码位于侧栏组件中,其中我的链接(即gatsby元素)也在其中。
return (
<nav>
<Link
className="hover:text-clr-accent flex items-center py-2 px-4 transition"
to="#home"
>
<i className="fa-solid fa-house w-6 text-center text-lg"></i>
<span className="pl-2 text-lg">Home</span>
</Link>
<Link
className="hover:text-clr-accent flex items-center py-2 px-4 transition"
to="#resume"
>
<i className="fa-solid fa-file w-6 text-center text-lg"></i>
<span className="pl-2 text-lg">Resume</span>
</Link>
<Link
className="hover:text-clr-accent flex items-center py-2 px-4 transition"
to="#about"
>
<i className="fa-solid fa-address-card w-6 text-center text-lg"></i>
<span className="pl-2 text-lg">About me</span>
</Link>
<Link
className="hover:text-clr-accent flex items-center py-2 px-4 transition"
to="#work"
>
<i className="fa-solid fa-briefcase w-6 text-center text-lg"></i>
<span className="pl-2 text-lg">My work</span>
</Link>
</nav>
);发布于 2022-02-14 15:56:43
来覆盖类。
https://stackoverflow.com/questions/71113808
复制相似问题