【发布时间】:2016-05-13 13:49:11
【问题描述】:
过去几天我一直在使用 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>
显然,这是我想要完成的一个非常简化的版本,但我希望你能明白。
TLDR:如何将状态从父级传递给子级作为道具?有没有办法通过父组件做到这一点?
任何帮助将不胜感激!
【问题讨论】:
标签: javascript reactjs state react-router