2017-08-30 20 views
1

我有一個名爲Layout的組件,它應根據路線呈現不同的child components。 父組件Dynimic子組件在相同的佈局路線上呈現

export default class Layout extends Component{ 
    render(){ 
     return (
      <div> 
       <div> 
        <div> 
         <Navbar/> 
         {this.props.sidebar} 
         {this.props.content} 
        </div> 
       </div> 
      </div> 
     ); 
    } 
} 

在我main.jxs我想呈現3路線使用Layout component不同ChildComponent爲側邊欄和內容類似的道具經過:

<Route path="/profile" component={sidebar: <Sidebar />, content: <Content />} /> 
<Route path="/user" component={sidebar: <Sidebar />, content: <User />} /> 
<Route path="/edit" component={sidebar: <Sidebar />, content: <Edit />} /> 

零部件均採用進口爲好。換句話說,我想動態地改變基於路線的佈局內容。我怎樣才能達到這個使用react-router-dom

+0

的可能的複製[配置在反應路由器V4嵌套路由(https://開頭stackoverflow.com/questions/44452858/configure-nested-routes-in-react-router-v4) –

+0

這怎麼可能是重複的呢?沒門!我試圖動態更改基於路由器的Layout子組件。我**不是**製作嵌套路線。 – danyhiol

+0

你不能像這樣將道具傳遞給組件,而是你可以配置嵌套的路線,因爲你希望你的應用看起來像 –

回答

0

如果我找到了你,你應該使用渲染功能作爲道具組件中的道具(反應路由器4) 爲了可以渲染多個組件。 見https://reacttraining.com/react-router/web/api/Route/render-func

此外,我提供未來小例子

https://jsfiddle.net/69z2wepo/85086/

1

你的做法是正確的,但你需要定義顯示佈局和其他途徑必須是子路由指數航線。

我用這作爲

<Route path="/" component={Layout} > 
     <IndexRoute components={{ body: LandingPage }} /> 
     <Redirect from="appdetail/" to="/" /> 
     <Route path="appdetail/:applicationId" components={{ body: AppDetailPage }} /> 
</Route>  

比我的佈局是這樣的:

export class Layout extends React.Component<ILayoutProps, void> { 

    /** 
    * Renders this object. 
    * 
    * @return A JSX.Element. 
    */ 
    public render(): JSX.Element { 

     const mainDivStyle: React.CSSProperties = { 
      width: "100%", 
      height: "100%", 
      top: "0px", 
      left: "0px", 
      backgroundColor: "#f2f2f2", 
      fontSize: "12px", 
      fontFamily: "Gotham" 
     }; 

     const contentDesktopStyle: React.CSSProperties = { 
      height: "100%" 
     }; 


     return (
      <div style={mainDivStyle}> 
        <div id="contentId" style={contentDesktopStyle}> 
         <Header />       
         { this.props.body } 
        </div> 
      </div> 
     ); 
    } 
} 
+0

我沒有測試你的答案,因爲它看起來相當複雜,亞瑟解決方案很好用,但我給了他一個大拇指,儘管你的確可以工作。 – danyhiol

+0

嗨:-) 沒問題...好的是你有一些工作解決方案:-) –