发布时间

React-router嵌套路由传值(render和children)

作者

Chad

小栗子:

例如: 我们的路由格式如下:

let router = [
  {
    path: "/",
    component: Rhome,
    exact: true,
  },
  {
    path: "/user",
    component: User,
    routes: [
      //嵌套路由
      {
        type: Route,
        path: "/user/",
        component: Main,
      },
      {
        type: Route,
        path: "/user/info/",
        component: UserInfo,
      },
    ],
  },
  {
    path: "/shop",
    component: Shop,
  },
  {
    path: "/news",
    component: NewsInfo,
  },
]

我们想在渲染时通过组件传值的方式,让父组件把子组件的路由传过去从而实现嵌套渲染。传统的父子组件传值在这里是用不了的。

  • 错误示范:

    <Route childRoutes="{val.routes}" />
    
  • 正确示范:

  • 传值:

return (
  <Route
    exact
    key={key}
    path={route.path}
    render={props => <route.component {...props} routes={route.routes} />}
  />
)

接收:

this.props.childrenRoute.map( (route, key) =>
<Route key="{key}" exact path="{route.path}" component="{route.component}" />
)

阐述:

  • 编程式导航,可以在一个组件中用 this.props.history.push("/path",{name:"hellow"}),来进行传参,传过去的值在 props.location.state 中
  • Route 里面还有两个重要的属性:renderchildren
// render是一个函数,语法:render={() => { return <div></div> }}
// 只要路由匹配了,这个函数才会执行
//
// children也是一个函数,不管路由是否匹配,这个函数都会执行
//
// 他们之间有优先级关系:render 的优先级总是高于 children,会覆盖 children

 <Fragment>
    <h1>header</h1>
    <Link to="/wiki/wikiList/">gogogo</Link>
    <Route
        path="/wiki/wikiList"
        render={
            ()=>{
                return <div>wikilist-children</div>
            }
        } //这个是只有当你路由匹配到了/wiki/wikiList才会执行
        // children={() => {
        //     return <div>wikilist-children</div>
        //   }
        // }    //这个是只要你的路由跳到wiki了,那children就会执行
    >
    </Route>
</Fragment>



Support

赞赏

如果这些内容对你有所帮助,欢迎赞赏支持。