【发布时间】:2018-09-27 12:42:00
【问题描述】:
我在尝试将道具传递给 this.props.children 时遇到困难
我有一个组件 MainLayout,我想将道具传递给 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>
);
}
}
但是,一旦我的路线得到了道具,它就会变成这样:
<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 ?
【问题讨论】:
-
你可以尝试使用
render方法作为<Route exact path="/" render={(props) => <PubsList {...props} />} /> -
这个问题以前被欺骗了。这个问题stackoverflow.com/questions/22639534/… 是相关的,但解决了一个不同的问题。虽然它的答案可以给出一些想法,但它们并不能直接回答这个问题。
标签: javascript reactjs react-router