笔记react router 4(二)

  上一篇我们提到react router 4的dom特性。那么这一次,我们来说一说4.X中的路由组件嵌套。

用过3.X的同学应该知道,路由组件的嵌套(即,路由的配置)方式是通过给<Route>添加子<Route>

例如,

<Route path='parent' component={Parent}>
  <Route path='child1' component={Child1} />
  <Route path='child2' component={Child2} />
  ...
</Route

这种方式看来,路由结构清晰明了。但由于不是真正的组件,因此在一些行为和需求上还是限制了我们。不过本人当初在使用时,并无不适,用得得心应手。^_^

再来看看4.X,当我们进入到正确的<Route>路径时,将会render其与其父组件,子组件作为父组件的子属性被传递

例如,

<Route path='/parent' render={()=>
  <Parent>  <Switch> <Route path='/parent/child1' component={Child1} /> <Route path='/parent/child2' component={Child2} /> </Switch>
  </Parent> } /> const Parent = () => ( <div> {this.props.children} </div> )

  因此,我们可以发现,在3.X中嵌套的路由层级对于两个组件来说是没有父子关系的,完全独立。而,在4.X中若要实现嵌套路由,子组件是要作为父组件的子属性传递进去的。也就是嵌套层级既体现了父子关系。

posted @ 2018-09-21 11:19  一江西流  阅读(257)  评论(0编辑  收藏  举报