簡體   English   中英

在React-Router中將狀態作為父級傳遞給子級?

[英]Passing state as props from Parent to Child in 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://facebook.github.io/react/docs/context.html上的示例

即使您使用react-router,我也可以在我的應用程序中使用它。

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>
  );
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM