Render multiple components in React Router

倖福魔咒の 提交于 2020-01-12 07:52:06

问题


I'm used to application layouts with multiple yield areas, i.e. for content area and for top bar title. I'd like to achieve something similar in React Router. For example:

<Router>
  <Route path="/" component = { AppLayout }>
    <Route path="list"
           component = { ListView }
           topBarComponent = { ListTopBar }/>
  </Route>
</Router>

AppLayout:

<div className="appLayout box">
  <div className="appLayout topBar">
    { -- display ListTopBar here -- }
  </div>
  <div className="appLayout content">
    { -- display ListView here -- }
  </div>     
</div>

Both child components should receive the same props.

How can I approach this?


回答1:


To passe multiple component you can do like this :

<Route path="groups" components={{main: Groups, sidebar: GroupsSidebar}} />
<Route path="users" components={{main: Users, sidebar: UsersSidebar}}>

See the doc here : https://github.com/ReactTraining/react-router/blob/v3/docs/API.md#named-components




回答2:


In v4, according to the docs, you can render multiple components like this:

<Route path='/some-path' render={props =>
  <div>
    <FirstChild />
    <SecondChild />
  </div>
} />



回答3:


Instead of using div's you can use Fragments. `

<Route path='/some-path' render={props =>
  <Fragment>
    <Child 1/>
    <Child 2/>
  </Fragment>
} />

`




回答4:


Another method is within the render method of route multiple passed components can be created using react.createElement

<Route render ={(props)=>React.createElement(Component1, {...props}},
                     React.createElement(Component2, {...props}}/> 



回答5:


To render multiple components you can do this:

<Route 
    path="/EditEmployee/:id"  
    render={(props) => 
        <div>
            <NavMenu />
            <EditEmployee {...props} />
        </div> 
    } 
/>

Here I'm passing parameter to specific conponent.



来源:https://stackoverflow.com/questions/37342997/render-multiple-components-in-react-router

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!