[英]React-Router-4 routing from another component
Is it possible to route a component from another component? 是否可以从另一个组件路由一个组件?
So normally it would be done like below 因此通常情况如下
<NavLink to="/link">link</NavLink>
<NavLink to="/anotherLink">link </NavLink>
<Switch>
<Route exact path="/link" component={linkComponent}/>
<Route path="/anotherLink" component={anotherLinkComponent}/>
</Switch>
but is it possible to have NavLink in one component which is loaded in the main component then route from the main component? 但是是否可以将NavLink放在一个组件中,该组件已加载到主要组件中,然后从主要组件路由? So have
NavLink
in one component and have Route
in the main component. 因此,在一个组件中具有
NavLink
,在主要组件中具有Route
。
The Nav component 导航组件
export default class Nav extends Component {
render() {
return (
<nav className="navigation">
<ul className="nav-container">
<li>
<NavLink to="/" className="nav-title">
First Page
</NavLink>
</li>
<li>
<NavLink to="second-page" className="nav-title">
Second Page
</NavLink>
</li>
<li>
<NavLink to="third-page" className="nav-title">
Third Page
</NavLink>
</li>
</ul>
<div className="nav-decoration">
</div>
</nav>
)
}
}
The App component 应用程序组件
import Nav from 'whateverthepath';
export default class App extends Component {
render() {
return (
<div>
<Nav/>
<Switch>
<Route exact path="/" component={Firstpage}/>
<Route path="/secondpage" component={Secondpage}/>
</Switch>
</div>
)
}
}
All the appropriate React imports are done 完成所有适当的React导入
That's definitely possible and your example should even work as is. 这绝对是可能的,您的示例甚至应该可以正常工作。 The biggest thing you'll need to make sure of is that your
<Route>
s were rendered as some point. 您需要确保的最大事情是您的
<Route>
被渲染为某个点。 The reason your example works is because you're rendering <Nav>
in the same render() method as your <Switch>
statement. 您的示例起作用的原因是因为您正在使用与
<Switch>
语句相同的render()方法来呈现<Nav>
。 If you were to instead just render <Nav>
without ever rendering the switch statement, then the NavLinks would take you somewhere that React Router hasn't been informed about. 如果您只渲染
<Nav>
而不渲染switch语句,那么NavLinks会将您带到尚未通知React Router的地方。 That's typically why your <Route>
s are almost always in your most parent component, to make sure they're rendered. 这就是为什么
<Route>
几乎总是位于父级组件中以确保它们被渲染的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.