2016-10-11 56 views
0

我最近使用React-router,發現它並不那麼直觀。 這是我的情況。我定義了一個無狀態的React組件「MainLayout」,它有兩個參數來包含「headerBar」組件和「children」組件。如何在react-router中指定組件的參數?

mainlayout.js:

const MainLayout = ({children,headerBar})=>{ 
    return (
    <div className="app"> 
     {headerBar} 
     <main> 
     {children} 
     </main> 
    </div> 
); 
} 
export default MainLayout; 

我的路線是這樣的:

routes.js:

export default (
    <Router history={browserHistory}> 
    <Route component={MainLayout}> -----> how to specify "headerBar" 
     <Route path="/" component={Home} /> 

     <Route path="widgets"> 
     <Route component={SearchLayout}> 
      <IndexRoute component={WidgetList} /> 
     </Route> 
     </Route> 

    </Route> 
    </Router> 
); 

在這種情況下,如何在路由指定 「headerBar」 「MainLayout」?

感謝

德里克

+0

你使用任何一種狀態容器? (Redux,flux ...) – Shota

+0

@shota不,我沒有使用任何容器。 – derek

回答

0

隨着反應的路由器,你可以在子路線聲明多個組件。該功能稱爲Named Components

這個主題已經在這裏治療過:Using React-Router with a layout page or multiple components per page

你應該寫財產以後這樣的:

<Route path="/" components={{body: Home, header: HeaderBar}} /> 

const MainLayout = ({body,header})=>{ 
    return (
    <div className="app"> 
     {header} 
     <main> 
     {body} 
     </main> 
    </div> 
); 
} 

問候

+0

我試過了,它不能工作,並得到「warning.js:36警告:失敗的道具類型:提供給'Route'的道具'組件'無效」。 – derek

+0

您使用的是哪個版本的反應路由器? –

+0

它是2.8.1謝謝。 – derek