我怎样才能使我的导航栏在react make show中仅在到达某个部分时才显示?在本例中,它是#about部分。因为目前我是通过检查滚动位置来实现的,所以问题出在较大的屏幕上,滚动位置会有所不同,所以我需要确保只有在达到#about时导航栏才会变得固定。目前我是这样做的:
const handleScroll = () => {
const position = window.pageYOffset;
setSrollPosition(position);
};
useEffect(() => {
window.addEventListener("scroll", handleScroll, { passive: true });
return () => {
window.removeEventListener("scroll", handleScroll);
};
}, []);
<TheAppBar position={scrollPosition > 670 ? "fixed" : "static"} id="about">
发布于 2020-10-04 04:27:13
通过利用Element.getBoundingClientRect()
在本例中,我们将一个ref
附加到#about
部分。Element.getBoundingClientRect().top
基本上会以像素为单位返回该元素与视口顶部之间的距离。在本例中,我从其中减去window.innerHeight
,这样我们就可以将条件从视口的底部而不是顶部建立。注意,您可能还希望考虑resize
事件,而不仅仅是scroll
事件,以获得完整的响应性。
function App() {
const aboutSectionRef = React.useRef(null);
const handleWindowScrollAndResize = e => {
console.clear();
if ((aboutSectionRef.current.getBoundingClientRect().top - window.innerHeight) <= 0) {
console.log("===== about section reached =====");
}
}
React.useEffect(()=>{
window.addEventListener("scroll", handleWindowScrollAndResize);
window.addEventListener("resize", handleWindowScrollAndResize);
return (()=>{
window.removeEventListener("scroll", handleWindowScrollAndResize);
window.removeEventListener("resize", handleWindowScrollAndResize);
})
}, [handleWindowScrollAndResize])
return(
<div>
<p style={{height: "1000px", minHeight: "120vh"}}>scroll down</p>
<div id="about" ref={aboutSectionRef} style={{height: "2000px", background: "grey"}}><h2>about section</h2> <p>I am the about section. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p></div>
<footer style={{height: "500px"}}>i am a footer</footer>
</div>
);
}
ReactDOM.render(<App/>, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.production.min.js"></script>
<div id="root"></div>
https://stackoverflow.com/questions/64188802
复制