環境:
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-router-dom": "^5.2.0",
路由配置
- routers.tsx文件內容
const routers = [
{
path: '/layout',
component: RouterLayoutConfig
},
{
path: '/component',
component: RouterComponentConfig
},
{
path: '',
component: RouterDashboardDeom,
children: [{
path: '/dashboard/details',
exact: true,
component: RouterDashboardDemoDetailsPage
}, { // 注意順序 默認匹配的放在最後
path: '',
exact: true,
component: RouterDashboardDeomList
}]
}
];
注意文件順序,如果默認匹配不放在最後,前面的是匹配不上(位置不對,二級路由/dashboard/details跳轉不了)
- App.tsx
export default function App() {
return (
<React.Fragment>
<Router>
<Switch>
{routers.map((route, i) => (
<RouteWithSubRoutes key={`rootRoute-${i}`} {...route} />
))}
</Switch>
</Router>
</React.Fragment>
);
}
- demo.tsx
import React, {Component} from 'react';
import {
Switch,
withRouter,
RouteComponentProps,
} from 'react-router-dom';
import {RouteWithSubRoutes} from '@share/routeWithSubRoutes';
interface DemoProps extends RouteComponentProps {
routes?: any[]
}
class RouterDashboardDeom extends Component<DemoProps> {
render() {
return (
<React.Fragment>
<Switch>
{
this.props.routes && this.props.routes.map((route, key) => {
return <RouteWithSubRoutes key={`subroute-${key}`} {...route} />
})
}
</Switch>
</React.Fragment>
)
}
}
export default withRouter(RouterDashboardDeom)
-
RouteWithSubRoutes
import React from "react";
import {
BrowserRouter as Router,
Switch,
Route,
} from 'react-router-dom';
// A special wrapper for <Route> that knows how to
// handle "sub"-routes by passing them in a `routes`
// prop to the component it renders.
export const RouteWithSubRoutes = function (route: any) {
return (
<Route
path={route.path}
exact={!!route.exact}
render={props => (
// pass the sub-routes down to keep nesting
<route.component {...props} routes={route.children} />
)}
/>
);
}