我正在关注这个教程:React Router Tutorial。在本教程中,作者做了两件事:
在另一条路线内嵌套子路线
render((
<Router history={hashHistory}>
<Route path="/" component={App}>
{/* make them children of `App` */}
<Route path="/repos" component={Repos}/>
<Route path="/about" component={About}/>
</Route>
</Router>
), document.getElementById('app'))
添加 {this.props.children}
render() {
return (
<div>
<h1>React Router Tutorial</h1>
<ul role="nav">
<li><Link to="/about">About</Link></li>
<li><Link to="/repos">Repos</Link></li>
</ul>
{/* add this */}
{this.props.children}
</div>
)
}
在这些步骤之后,当我单击About
或上的链接时Repos
,我不会转到新屏幕,但它会在同一屏幕中呈现。我不明白这里的逻辑。如果我可以执行上述 2 个步骤,为什么 React Router 会在同一屏幕上呈现。请为我解释。
这里的想法是通过显示应该出现在每个子路由上的元素来减少重复。在您的情况下,它是导航。你更喜欢什么——必须在每个页面上手动添加导航还是自动添加到每个子路由?
React 是如何通过 children props 实现的,正如官方 React 文档所说:
在同时包含开始标签和结束标签的 JSX 表达式中,这些标签之间的内容作为特殊道具传递:props.children。
如果你想避免这种行为,要么你应该避免嵌套,要么你可以从 App 组件中删除导航并使其成为一个单独的组件。然后就可以将其一一包含在每个子组件中。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句