這個方法會使得路由標籤比較分散,子組件咱們必須直接將Route標籤寫入到父組件之中,並且路由必須包含根路徑.react
// Dashboard.jsx import Menu from '~/components/Menu/Menu'; import React from 'react'; import {Route,Switch} from "react-router-dom"; import Index from '~/container/Index/Index'; import TaskList from '~/container/TaskManage/TaskList/TaskList' const routes = [ { path: "/Dashboard/Index", component: Index }, { path: "/Dashboard/TaskManage/TaskList", component: TaskList } ]; class Dashboard extends React.Component{ constructor(props, context ) { super(props, context ); } render(){ return( <div> <Menu/> <div className='container'> <div> {routes.map((route, index) => ( <Route exact key={index} path={route.path} component={route.component} /> ))} </div> </div> </div> ) } } export default Dashboard
component使用this.props.children進行嵌套渲染,Dashboard爲父組件,Index和TaskList爲子組件react-router
// router.js <Router history={history}> <Switch> <Route exact path="/" component={Login}/> <Route path="/" render={({history,location,match}) => ( <Dashboard history={history} location={location} match={location}> <Route path="/Dashboard/Index" component={Index}></Route> <Route path="/Dashboard/TaskManage/TaskManageIng" component={TaskManageIng}></Route> <Route path="/Dashboard/TaskManage/TaskList" component={TaskList}></Route> <Route path="/Dashboard/TaskManage/TaskResource" component={TaskResource}></Route> </Dashboard> )} /> </Switch> </Router> // Dashboard.jsx import Menu from '~/components/Menu/Menu'; import React from 'react'; class Dashboard extends React.Component{ constructor(props, context ) { super(props, context ); } render(){ return( <div> <Menu/> <div className='container'> <div> {this.props.children} </div> </div> </div> ) } } export default Dashboard