[英]Scrolling to a component on the same page using react-router
我有一個單頁反應應用程序(而是所有內容都在頁面上),我希望使用 react-router 滾動到同一頁面上的必要組件。 這是我的導航代碼,
class Navbar extends React.Component {
constructor(props){
super(props)
}
renderMain() {
return (
<div></div>
//return home
);
}
handleScroll = e => {
e.preventDefault();
const main = this.main.current;
window.scrollTo({
top: main.offsetTop,
left: 0,
behavior: "instant"
});
};
render(){
return (
<div className="navbar container">
<div className="logo">
<img src={logo}></img>
</div>
<BrowserRouter>
<div className="navigation">
<ul>
<li className="listPadding"><Link onClick={this.handleScroll}
to="/"
className="navLink"
activeClassName="activeRoute" />HOME</li>
<li className="listPadding"><Link onClick={this.handleScroll}
to="/whats-crcl" className="navLink"
activeClassName="activeRoute"/>WHAT'S CRCL?</li>
<li className="listPadding"><Link onClick={this.handleScroll}
to="/founders" className="navLink"
activeClassName="activeRoute"/>THE FOUNDERS</li>
<li className="listPadding"><Link onClick={this.handleScroll}
to="/careers" className="navLink"
activeClassName="activeRoute"/>WE'RE HIRING!</li>
<li className="button"><Link to=""/>READ THE BLOG</li>
</ul>
<Switch>
<Route exact path="/" component={() => this.renderMain()} />
<Route exact path="/whats-crcl" render={() => Snippets} />
<Route exact path="/the-founders" render={() => MainContent} />
<Route exact path="/whats-crcl" render={() => Careers} />
<Route render={() => <h1>Page not found</h1>} />
</Switch>
</div>
</BrowserRouter>
</div>
);
}
}
這是我的 CSS:
.navigation {
ul {
li {
font-family: 'Roboto', sans-serif;
font-size: 1.2em;
font-weight: 400;
color: #ffffff;
list-style: none;
display: inline-block;
a.navLink:link {
color: #fff;
font-size: 1.6rem;
line-height: 1.6rem;
text-decoration: none;
}
a.navLink:visited {
color: #fff;
}
a.navLink:hover {
color: #595959;
}
a.navLink:active {
color: #595959;
}
}
}
}
.activeRoute {
background-color: yellow;
border-bottom: 0.4rem solid teal;
cursor: not-allowed;
}
我是 React 的新手。 我的問題是:
a
標簽的情況一樣?這可以使用這個react-scroll來實現。
我把重要的代碼片段放在這里。 詳細用法在這里。
在導航組件中。
...
import { Link } from 'react-scroll';
...
<ul>
<li className="listPadding">
<Link onClick={this.handleScroll}
to="about"
activeClass="active"
spy={true}
smooth={true}
>
ABOUT
</Link>
</li>
</ul>
而 about 組件需要有唯一的 id about
。 片段看起來像這樣。
const About = () => {
return (
<div id="about">
...
</div>
);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.