mre*_*345 10 javascript state reactjs react-router
在过去的几天里我一直在使用React-Router,我一直很喜欢它!我遇到的一个问题是我找不到将状态从父组件传递到子组件的最佳方法.我一直在看几个堆栈溢出和博客帖子,但我似乎无法找到我想要的东西.这是一个关于我正在寻找的非常简化的例子.
class App extends React.Component {
constuctor(props) {
super(props);
this.state = {name:"helloworld", lastname:"world hello"};
}
render() { // SOMETHING LIKE THIS WOULD BE PREFFERED
if (this.props.children.name == "Home") {
{this.props.children myname={this.state.name}}
}
else if (this.props.children.name = "Account") {
{this.props.children anotherprop={this.state.lastname}}
}
}
}
class Home extends React.Component {
render() {
return (
{this.props.myname}
);
}
}
class Account extends React.Component {
render() {
return (
{this.props.lastname}
);
}
}
//ROuting config - (Only the routes not the config)
<Route path="/" component={App}>
<IndexRoute component={Home} />
<Route path="account" component={account} />
</Route>
Run Code Online (Sandbox Code Playgroud)
显然这是我想要完成的非常简化的版本,但我希望你能得到它.
TLDR:如何将状态从父级传递给子级作为道具?有没有办法通过父组件来做到这一点?
任何帮助将不胜感激!
我所做的就是使用cloneElement来创建克隆,我可以将我的状态道具添加到该克隆:
return React.cloneElement(
this.props.children,
{appName: 'Foo'}
);
}
Run Code Online (Sandbox Code Playgroud)
小智 2
您可以使用上下文将数据从父组件传递到子组件。请参阅https://facebook.github.io/react/docs/context.html的示例
即使您使用react-router,这也能完美工作,我在我的应用程序中使用它。
| 归档时间: |
|
| 查看次数: |
7203 次 |
| 最近记录: |