2016-06-24 66 views
2

這是一個關於反應比一個具體問題的體系結構問題,但什麼被認爲是管理狀態/道具佈局組件和幾個子組件的基礎上網址?基於URL改變組件與反應路由器

注:我知道類似的問題已經被問到,但這有點不同。 [How to update ReactJS component based on URL/path with React-Router

可以說我有類似下面的代碼:配置文件頁面(主要佈局視圖)與屬性子段(設置,偏好,帳戶信息等)的導航鏈接,以及一個主面板,其中每個子部分被渲染。

所以現在我想有這樣的事情: 我的路由器 routes.js

<Router history={browserHistory}> 
    <Route path='/profile' component={Profile} > 
    <IndexRoute component={Summary} /> 
    <Route path='/profile/settings' component={Settings} /> 
    <Route path='/profile/account' component={Account} /> 
    <Route path='/profile/preferences' component={Preferences} /> 
    </Route> 
</Router> 

和我的個人資料佈局組件的一個精簡版 profile.js

class Profile extends React.Component { 

    constructor(props) { 
    super(props) 
    } 

    render(){ 

    let pathName = this.props.location.pathname; 

    return(
     <div className='container profile-page'> 
     <div className='side-nav'> 
      <ul> 
      <li><Link to='/profile'>Summary</Link></li> 
      <li><Link to='/profile/settings'>Settings</Link></li> 
      <li><Link to='/profile/account'>My Account</Link></li> 
      <li><Link to='/profile/preferences'>Preferences</Link></li> 
      </ul> 
     </div> 
     <div className='main-content'> 
     {this.props.children} 
     </div> 
     </div> 
    ) 
    } 
} 

export default Profile; 

所以這種作品。子組件將基於url進行呈現。但是,我如何管理國家和道具?我瞭解React和Flux的方式,我希望Profile組件能夠管理狀態並監聽我商店中的更改,並將這些更改傳播給其子項。它是否正確?

我的問題是,似乎沒有一種直觀的方式將道具傳遞給由this.props.children呈現的組件,這讓我感覺像是我當前的體系結構和/或對flux的理解不正確。

一點指導將不勝感激。

回答

1

我覺得你在做什麼很完美。你走在正確的道路上。

有這麼陣營爲您提供了將採取的正是你不能確定如何實現(way to pass props to components rendered by this.props.children

首先照顧,你需要看一看cloneElement

的API的組合

它基本上需要一個React元素,克隆它,並返回另一個可以根據需要完全更改,更改或替換的道具。

此外,將它與Children Utilities - 通過提供給頂層組件的孩子進行循環並逐個對每個元素進行必要的更改。

擬議樣品的使用可能是那樣簡單

<div className='main-content'> 
    {React.children.map(this.props.children, (child, index) => { 
     //Get props of child 
     const childProps = child.props; 

     //do whatever else you need, create some new props, change existing ones 
     //store them in variables 

     return React.cloneElement(child, { 
      ...childProps, //these are the old props if you don't want them changed 
      ...someNewProps, 
      someOldPropOverwritten, //overwrite some old the old props 
     }); 
    )} 
</div> 

使用這些工具來創建真正通用的,可重用的組件,隨時隨地。來自Children的更常用的實用程序是map,forEachtoArray。每個人都有各自的目標。

希望這會有所幫助。

+1

好吧,這樣做現在更有意義。非常感謝您提供全面的答案。 – jmknoll

+0

非常歡迎,這是董事會的目的。希望它也能幫助別人。對於一個好問題的讚譽,幾乎沒有這些日子。 –