我在尝试将props传递给 this.props.children 时遇到困难
我有一个组件 MainLayout 并且我想将props传递给 this.props.children 但他的孩子是这样的:
AppRouter.js
export default class AppRouter extends Component {
render() {
return (
<HashRouter>
<Switch>
<MainLayout>
<Route exact path="/" component={PubsList} />
<Route exact path="/add-pub" component={AddPub} />
<Route exact path="/add-pub/:id" component={AddPub} />
</MainLayout>
</Switch>
</HashRouter>
)
}
}
MainLayout.js :我使用 React.Children 和 React.CloneElement 来传递 props
export default class MainLayout extends Component {
constructor(props) {
super(props);
this.state = {
foo: "foo"
};
render() {
return (
<div className="container" >
<Menu inverted color='teal' fixed="top" style={{ margin: "0", padding: "20px", borderRadius: "0", display: "block" }}>
<Link to="/">
<Header as='h2' content='PandaBar' floated="left" style={{ color: "white", margin: "0" }} />
</Link>
</Menu>
<div className="content" style={{ marginTop: "70px", overflow: "hidden" }} >
{React.Children.map(this.props.children, child => {
return React.cloneElement(child, { foo: this.state.foo })
})}
</div>
</div>
);
}
}
但是,一旦我的路线获得props,它看起来像这样:
<HashRouter>
<Switch>
<MainLayout>
<Route exact path="/" component={PubsList} foo="foo"/>
<Route exact path="/add-pub" component={AddPub} foo="foo"/>
<Route exact path="/add-pub/:id" component={AddPub} foo="foo"/>
</MainLayout>
</Switch>
</HashRouter>
那么,如何使用此配置将我的props foo 传递给我的组件 PubsList 和 AddPub?