将道具传递给this.props.children

时间:2018-05-15 03:53:33

标签: javascript reactjs redux react-router-v4 react-router-dom

我是React的新手,我遇到了将自定义道具传递给this.props.children的问题。我已经尝试了React.cloneElement,当我在我创建它的类中执行console.log时,我可以看到prop。但是当我尝试通过它时它会丢失。我不知道是否React-Router-Dom正在做某事导致道具不能通过。任何帮助将不胜感激。

我使用GitHub中的Create-React-App启动了这个项目。我安装了以下软件。

"react": "^16.3.2",
"react-dom": "^16.3.2",
"react-redux": "^5.0.6",
"react-router-dom": "^4.2.2",
"react-scripts": "1.1.4",
"redux": "^3.7.2",

在App.js中

render() {
 return (
  <Provider store={store}>
    <BrowserRouter> 
    <Switch>
      <Route exact path="/" component={LoginPage} />
      <Route path="/Login" component={LoginPage} />
      <RootPage>
        <Route path="/TestPage" component={testPage} />
      </RootPage> 
    </Switch>
   </BrowserRouter>
  </Provider>
 );
}
RootPage.js(Parent)中的

render() {
    const { classes, theme, children } = this.props;

    var childrenWithProps = React.Children.map(children, child => React.cloneElement(child, { doSomething: "Test String" }));

    console.log(childrenWithProps)
    return (
        <div>
           {childrenWithProps}
        </div>
    );
}

console.log上面的RootPage.js我可以看到道具“doSomething”。

TestPage.js(Child)中的

render(){
    const { classes, theme } = this.props;

    console.log(this.props)

    return (
        <div> 
        </div>
    );
}

在TestPage.js中的上述console.log我看不到“doSomething”道具我通过了。

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

props展开到TestPage组件的Route组件中。

<RootPage>
  <Route path="/TestPage" render={props => <TestPage {...props} /> }/>
</RootPage>
相关问题