2016-10-11 52 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