我試圖做一個(gè)響應(yīng)性的導(dǎo)航條,當(dāng)它滾動(dòng)到導(dǎo)航條的高度(目前是80px)時(shí),它會(huì)調(diào)整大小,但是當(dāng)我滾動(dòng)到大約80px時(shí),它會(huì)在折疊和未折疊版本之間不停地旋轉(zhuǎn)。我試著用條件句和四舍五入的方法來(lái)解決問(wèn)題,但是兩種方法都沒(méi)有解決問(wèn)題。誰(shuí)能給我解釋一下為什么會(huì)這樣,以及一個(gè)可能的解決方案(也許是window.scrollY的替代方案?)
import { useState, useEffect } from "react";
import { NavLink } from "react-router-dom";
import "./Navbar.css";
const Navbar = () => {
const [scrolled, setScrolled] = useState(false);
useEffect(() => {
const onScroll = () => {
console.log("condition not rounded", window.scrollY);
if (window.scrollY >= 80) {
setScrolled(true);
} else if (window.scrollY <= 79) {
setScrolled(false);
}
};
window.addEventListener("scroll", onScroll);
return () => {
window.removeEventListener("scroll", onScroll);
}
}, []);
return (
<div className="navbar-container">
<div className={`navbar ${scrolled ? "navbar-collapse" :""}`}>
<div>
<NavLink className={`nav-link ${scrolled ? "nav-link-collapse": ""}`} to="/">HOME</NavLink>
</div>
<div>
<NavLink className={`nav-link ${scrolled ? "nav-link-collapse": ""}`} to="/menu">MENU</NavLink>
</div>
<div>
<NavLink className={`nav-link ${scrolled ? "nav-link-collapse": ""}`} to="/market">MARKET</NavLink>
</div>
<div>
<NavLink className={`nav-link ${scrolled ? "nav-link-collapse": ""}`} to="/about">ABOUT US</NavLink>
</div>
<div>
<NavLink className={`nav-link ${scrolled ? "nav-link-collapse": ""}`} to="/contact">CONTACT US</NavLink>
</div>
</div>
</div>
);
};
export default Navbar;
.navbar-container {
background-color: #010a10;
height: auto;
position: sticky;
top: 0;
z-index: 1;
}
.navbar {
display: flex;
justify-content: center;
padding: 0 calc((100vw - 1000px) / 2);
align-items: center;
flex-flow: row wrap;
transition: all 0.3s ease;
}
.navbar-collapse {
margin-right: 0;
padding-right: 0;
margin-left: auto;
flex-wrap: nowrap;
justify-content: flex-end;
transition: all 0.3s ease;
}
.nav-link {
display: inline-block;
color: #FFFBF2;
text-decoration: none;
font-weight: 700;
font-size: 1.2rem;
padding: 1.6rem 3.5rem;
transition: all 0.3s ease;
}
.nav-link-collapse {
font-size: 0.8rem;
padding: 1rem 2rem;
flex-shrink: 1;
transition: all 0.3s ease;
}
.active {
color: #c10206;
background-color: #282829;
}
.nav-link:hover {
transition: color 0.3s ease;
color: #c10206;
}