[英]Why this pass props into this.props.children doesn't work?
I tried to pass in props to this.props.children using the following code 我尝试使用以下代码将道具传递给this.props.children
export default class Home extends Component {
render(){
var children = React.Children.map(this.props.children, function (child) {
return React.cloneElement(child, {
foo: "1"
})
});
return(
<div className="bla">
<h1>WeDate</h1>
<div className="child">
{children}
</div>)
}
}
But I can't read this.props.foo in my searchDate component when it renders normally. 但是当它正常呈现时,我无法在我的searchDate组件中读取this.props.foo。 The following is my react router.
以下是我的反应路由器。
render(
<Router>
<Home>
<Switch>
<Route exact path="/"><Redirect to="/search" push/></Route>
<Route exact path="/search" component={SearchDate}></Route>
</Switch>
</Home>
</Router>
,document.getElementById('app')
);
the children to your Home component are not the Routes but the Switch and hence foo is not passed down as props to the respective components. Home组件的子代不是Route而是Switch,因此foo不会作为props传递给各个组件。 What you need to do is to nest your Routes is the Home component and not as children
您需要做的就是嵌套您的路线是“家庭”组件,而不是作为子组件
Home 家
export default class Home extends Component {
render(){
return(
<div className="bla">
<h1>WeDate</h1>
<div className="child">
<Switch>
<Redirect from="/" exact to="/search"/>
<Route exact path="/search" render={(props) => <SearchDate foo={'1'} {...props}/>}>
</Switch>
</div>)
}
}
Routes 路线
render(
<Router>
<Home />
</Router>
,document.getElementById('app')
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.