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

本文通过一个小例子探讨React-router的嵌套路由传值,解释了使用`render`和`children`属性进行传值的正确方法。错误示范与正确示范对比展示了如何在组件中利用`this.props.history.push`进行编程式导航,并指出传参可以通过`props.location.state`获取。同时,提到了Route组件的`render`和`children`属性在传值中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

小栗子:

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

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里面还有两个属性,render和children
-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>




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值