![](/img/trans.png)
[英]How to pass props through this.props.children() not this.props.children
[英]Pass Props to this.props.children
我是React的新手,在将自定义道具传递给this.props.children
。 我已经尝试过React.cloneElement
,当我在创建它的类中执行console.log时可以看到道具,但是当我尝试React.cloneElement
它时它就会丢失。 我不知道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中(父)
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>
);
}
通过上面RootPage.js
的console.log
,我可以看到道具“ doSomething”。
在TestPage.js中(子级)
render(){
const { classes, theme } = this.props;
console.log(this.props)
return (
<div>
</div>
);
}
在上述TestPage.js中的console.log
中,我看不到我通过的“ doSomething”道具。
感谢您的任何帮助。
将props
从Route
组件传播到TestPage
组件。
<RootPage>
<Route path="/TestPage" render={props => <TestPage {...props} /> }/>
</RootPage>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.