【发布时间】:2020-08-15 14:16:42
【问题描述】:
我有一个单页网站,每次点击导航项都会滚动到不同的部分。目前,如果我从其中一个部分滚动,导航栏是不知道的,并且不允许滚动到先前单击的部分。
我希望能够跟踪用户在页面上的位置并让导航栏做出相应的响应。
所有的应用组件都在这里渲染:
function App() {
const homeRef = useRef();
const aboutRef = useRef();
const portRef = useRef();
const contactRef = useRef();
const [selection, setSelection] = useState("home");
const handleSelect = (select) => {
setSelection(select);
};
useEffect(() => {
if (selection === "home") {
homeRef.current.scrollIntoView({
behavior: "smooth",
block: "start",
});
}
if (selection === "about") {
aboutRef.current.scrollIntoView({
behavior: "smooth",
block: "start",
});
}
if (selection === "portfolio") {
portRef.current.scrollIntoView({
behavior: "smooth",
block: "start",
});
}
if (selection === "contact") {
contactRef.current.scrollIntoView({
behavior: "smooth",
block: "start",
});
}
},[selection]);
return (
<div className="allShared">
<Navigation className="nav" onNavSelection={handleSelect}></Navigation>
<div ref={homeRef}>
<Home></Home>
</div>
<div ref={aboutRef}>
<About></About>
</div>
<div ref={portRef}>
<Portfolio></Portfolio>
</div>
<div ref={contactRef}>
<Contact></Contact>
</div>
</div>
);
}
export default App;
子组件将点击哪个导航项传递给父组件。
const Navigation = (props) => {
const sendData = (key) =>{
props.onNavSelection(key)
}
return (
<Navbar
className="nav "
collapseOnSelect
expand="lg"
fixed="top"
bg="dark"
variant="dark"
style={{
opacity: "0.9",
}}
>
<Navbar.Toggle aria-controls="responsive-navbar-nav" />
<Navbar.Collapse id="responsive-navbar-nav">
<Nav className="mr-auto mr-5" onSelect={(selectedKey)=>sendData(selectedKey)}>
<Nav.Link eventKey="home">Home</Nav.Link>
<Nav.Link eventKey="about">About</Nav.Link>
<Nav.Link eventKey="portfolio">Portfolio</Nav.Link>
<Nav.Link eventKey="contact">Contact</Nav.Link>
<Nav.Link target="_blank" href="">CV</Nav.Link>
</Nav>
</Navbar.Collapse>
</Navbar>
);
};
export default Navigation;
感谢任何指针和提示。
【问题讨论】:
标签: javascript reactjs