【问题标题】:Passing props to children components with react-router v4使用 react-router v4 将 props 传递给子组件
【发布时间】:2017-03-18 12:46:40
【问题描述】:

之前在 react-router v3.* 我通过

将 props 传递给子组件
React.cloneElement(this.props.children, this.props)

如何在 react-router v4 中使用新的<Match /> API 完成此操作

到目前为止,我想出的解决方案是在<Match /> API 中使用render 方法:

<Match pattern="/" render={() => <ChildComponent {...this.props} />} />

使用 ES6 扩展语法将 props 传递给子组件。有没有更好的方法可以将所有标准道具(位置、模式、路径名、isExact)带到子组件?

【问题讨论】:

    标签: javascript reactjs react-router react-router-component


    【解决方案1】:

    根据the render code of v4.0.0-alpha5判断,您有以下两种选择:

    <Match pattern="/" render={props => <ChildComponent {...props} {...this.props} />} />
    <Match pattern="/">{({matched, ...props}) => {
        return matched ? <ChildComponent {...props} {...this.props} /> : null;
    }}</Match>
    

    另见Match API documentation.

    【讨论】:

    • 我正在使用 react-router v4.0.0-2,因为我不确定 alpha 版本的稳定性。我猜 react-router v4 仍在开发中,我注意到即使 npm 只发布 v3,除非你明确要求版本 4
    • 看起来相关的渲染代码在alpha-2中是一样的。但是,是的,我认为 v4 仍然是非常实验性的。如果您正在寻找稳定的东西,我会改用 v3。
    • 是的。没有意识到 props 是传递给渲染函数的参数。谢谢!这可能是目前最好的解决方案
    猜你喜欢
    • 2015-07-12
    • 2017-09-14
    • 2015-10-30
    • 2017-10-24
    • 1970-01-01
    • 2018-12-27
    • 2017-02-13
    • 1970-01-01
    • 2016-03-19
    相关资源
    最近更新 更多