微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

JavaScript – 将状态作为道具从父母到孩子在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>

显然,这是一个非常简化的版本,我想完成,但我希望你得到的照片.

TLDR:如何将父母的状态作为道具传递给孩子?有没有办法通过父组件这样做?

任何帮助将不胜感激!

解决方法

我所做的仅仅是使用cloneElement来创建一个克隆,我可以将我的状态道具添加到克隆中:
return React.cloneElement(
        this.props.children,{appName: 'Foo'}
    );
}

原文地址:https://www.jb51.cc/js/153484.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐