react router给Route组件设置自定义属性

场景分析

当使用Route在页面内做跳转时,有时想要传一些自定义属性到子路由组件中,而常用的<Route path={xxx} component={Component} test={123}/>这种方式设置test属性是无效的,因此需要用到Route的第二种渲染方式

解决办法

Route组件的render方法

<Route path="/home" render={(props) => <Component test={123} {...props}/>}/>

应用拓展

在前端路由嵌套后,当子路由组件想要在unmount后刷新父路由组件时,可以通过上述方法将父路由的加载数据方法传递到子组件再调用

componentDidMount(){
    this.getLists(); //获取数据列表方法
}
render(){
    <div className="parentComponent">
        <ul>
            {this.state.list.map((item)=>{
                return (<li>{item.value}</li>)
            })}
        </ul>
        <Route path={`${match.url+'/:id'}`} render={(props)=><AddMail loadLists={this.getTelLists} {...props}/>}/>
    </div>
}

发布了114 篇原创文章 · 获赞 146 · 访问量 25万+

猜你喜欢

转载自blog.csdn.net/Sophie_U/article/details/80651043