【问题标题】:Passing state as props from Parent to Child in React-Router?在 React-Router 中将状态作为道具从父级传递给子级?
【发布时间】: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


    【解决方案1】:

    lufte - 如果您的原始代码如下所示:

    render() {
      return(
        <div className="wrapper">
        {this.props.children}
        </div>
      );
    }
    

    那么将数据传递给组件的子组件的修改后的代码将是:

    render() {
      var clonedChildren = React.cloneElement(this.props.children, {myProp: myValue});
      return(
        <div className="wrapper">
        {clonedChildren}
        </div>
      );
    }
    

    【讨论】:

      【解决方案2】:

      我所做的只是使用 cloneElement 创建一个克隆,然后我可以将我的状态道具添加到该克隆:

      return React.cloneElement(
              this.props.children, 
              {appName: 'Foo'}
          );
      }
      

      【讨论】:

      • 您介意分享整个解决方案吗?我不明白我应该把这段代码放在哪里。
      【解决方案3】:

      您可以使用上下文将数据从父组件传递到子组件。请参考https://facebook.github.io/react/docs/context.html的示例

      即使您使用 react-router,这也能完美运行,我在我的应用程序中使用它。

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-09
      • 2016-09-26
      • 2023-01-13
      • 1970-01-01
      • 1970-01-01
      • 2018-09-25
      • 1970-01-01
      • 2021-04-25
      相关资源
      最近更新 更多