In the example below, I have two functional components that give the idea of being separate pages, though, of course, they only display different colored <div>
boxes.
const Home = () =>
<div style={{background:'red', height: 100, width: 100}}></div>;
const About = () =>
<div style={{background:'blue', height: 100, width: 100}}></div>;
Now, if I wanted to create a navigation bar that links to certain parts of my site -- ignoring the possible wrong use of the <a>
links, but it is to show that I want those to render other parts of the site as a response to clicking on a Navbar
option.
const Navbar = () =>
<div>
<a href='#'>Home</a>
<a href='#'>About</a>
</div>;
If I have a component named App
that renders different pages for me:
const App = () =>
<div>
<Navbar />
// Render current page here; default is the `Home` component.
</div>;
ReactDOM.render(<App />, document.getElementById('app'));
How could I actively update my App
component to render different pages based off the clicking of links, or elements, in my Navbar
?
EDIT:
Soviut和finalfreq渲染其他组件,谢谢您的回答!我来自Codecademy的ReactJS课程,所以过渡到Javascript和React的“真实世界”有点困难,因为我必须学习ES6,并且不了解大多数JS库。无论如何,我感谢你们指出了我react-router
的方向,并给了我一个如何在没有它的情况下实现我的目标的例子。欢呼声。
答案 0 :(得分:1)
这就是react-router
的目的。
虽然不推荐手动操作,但它可以通过发出点击事件来调用从包含你的&#34;页面&#34;的父组件传入的回调函数。该回调将告诉父容器单击了哪个导航链接,它将决定显示哪个页面以及停止渲染哪个页面。
答案 1 :(得分:1)
每个页面都没有路由器/控制器,你可以这样做:
const pages = ['array', 'of', 'pages'];
class App extends React.Component {
constructor(props) {
super();
this.state = {
activePage: pages[0]
}
}
switchPage = (page) => {
this.setState({
activePage: page
})
}
renderActivePage = () => {
switch(this.state.activePage) {
case 'home':
return <HomeComponent />
}
}
render() {
return (
<div>
<Navbar switchPageFunction={this.switchPage}/>
{renderActivePage()}
</div>;)
}
}
然后只需将onclick设置为您的标签,实际上是switchPageFunction并将页面名称作为参数传递。然后,父组件将接收更新,更新其自己的状态,并呈现正确的组件。
我不建议使用这条路线,而是选择仅针对此用例构建的react-router