【问题标题】:React Router - Passing match via props to a component rendered using Route::renderReact Router - 通过道具将匹配传递给使用 Route::render 渲染的组件
【发布时间】:2018-12-19 02:03:53
【问题描述】:

这个Route是使用render prop来渲染一个带有props的子组件:

<Route to='/path/:id' render={ () => (<ChildComponent myProp={myProp} match={this.props.match}/>)} />

但是传递的match 的版本似乎与父组件的路由状态“匹配”,因此没有在match.route.params 下注册id

我想像这样的一些解决方案可能会同步路由状态:

<Route to='/path/:id' render={ () => (withRouter(<ChildComponent myProp={myProp} />))} />

但这只会导致一个错误,说子组件不能是函数......

处理这个问题的正确方法是什么?

【问题讨论】:

    标签: reactjs react-router


    【解决方案1】:

    由于您要传递 match 参数,因此不应传递父可用的参数,而应传递与 Route 相关的参数。 render prop 回调接收可以传递的Router Props

    <Route to='/path/:id' render={(routerProps) => (<ChildComponent {...routerProps} />)} />
    

    或者你可以简单地写

    <Route to='/path/:id' component={ChildComponent} />
    

    在这种情况下,它会将相关的路由器道具传递给组件。

    在子组件中,您可以访问匹配道具,如

    this.props.match.params.id
    

    【讨论】:

      猜你喜欢
      • 2023-03-09
      • 2018-05-13
      • 1970-01-01
      • 1970-01-01
      • 2016-03-19
      • 2019-12-05
      • 1970-01-01
      • 2020-07-26
      • 1970-01-01
      相关资源
      最近更新 更多