如何将所有父道具传递给使用{this.props.children}的所有嵌套路由子项

时间:2017-12-13 05:11:11

标签: reactjs react-router-dom

我想将所有父道具传递给嵌套路线中的儿童路线

<NestedRoute path="/Resident" component={Resident} >
    <SubRoute path="/dashboard" component={Dashboard} />
    <SubRoute path="/policies/index" component={Policies}/>
    <SubRoute path="/pages/create-account" component={CreateAccount} />
    <SubRoute path="/pages/empty-page" component={EmptyPage} />
    <SubRoute path="/pages/under-maintenance" component={UnderMaintenance} />
    <SubRoute path="/pages/error-page" component={ErrorPage} />
</NestedRoute>

我正在使用{this.props.children}显示此路线。我想使用this.props.history.push以嵌套路由中的页面之间以编程方式导航 我正在得到未定义的错误推送。所以我想传递所有的父道具。但我不知道怎么做。

我试过了

React.Children.map(this.props.children, (child => React.cloneElement(child, this.props)))

它不起作用。我的最终目标是以编程方式从嵌套路线导航。

1 个答案:

答案 0 :(得分:1)

component代替Route,如果您使用render进行组件呈现,则可以通过这种方式实现。

<Route path = "/dashboard" render = {
    (props) => (<Dashboard {...props}/>)
} />

<Route path = "/policies/index" render = {
(props) => (<Policies {...props}/>)
} />