1、结构目录
2、路由配置文件,参照的vue-router
config.js
import Login from '../view/Login.js'; import System from '../view/System.js'; import Bus from '../view/Bus.js'; import Bus22 from '../view/Bus22.js'; const routes = [ { path: "/",component: Login,exact: true"/system/bus"default routes;
3、路由主体,使用react-router-dom,详细文档里面也有其它的例子和API
import routes from './config'; import React,{Component} from 'react'; import { BrowserRouter as Router,Switch,Route,Redirect,} from "react-router-dom"; /*一级路由*/ class First extends Component { render() { return ( <Router> <Switch> {routes.map((route,i) => { if (route.auth) {//根据配置是否检测登录 ( <PrivateRoute key={i} path={route.path}> <route.component/> </PrivateRoute> ) } else { return (<RouteWithSubRoutes key={i} {...route} />) } } )} </Switch> </Router> ); } } 二级路由 class SystemRouter extends Component { render() { ( <Switch> {routes[1].routes.map((route,i) => { 根据配置是否检测登录 ( <PrivateRoute key={i} path={route.path}> <route.component/> </PrivateRoute> ) } } })} </Switch> ); } } export { First,SystemRouter }; A special wrapper for <Route> that knows how to // handle "sub"-routes by passing them in a `routes` prop to the component it renders. /*开放路由*/ function RouteWithSubRoutes(route) { ( <Route exact={route.exact} path={route.path} render={props => ( pass the sub-routes down to keep nesting <route.component {...props} routes={route.routes}/> )} /> ); } 登录检测路由 PrivateRoute({children,...rest}) { let isAuthenticated = sessionStorage.auth; Route {...rest} render={({location}) => isAuthenticated ? ( children ) : ( <Redirect to={{ pathname: "/" ) } /> ); }
4、一级路由的使用,在App.js
import React from 'react'; import './App.css'; import {First} from './router/index' App() { ( <First/> ); } export default App;
5、二级路由的使用,在一级路由的组件文件中,本例是System.js
import React,{Component} from 'react'; import {SystemRouter} from '../router/index'; import { withRouter } from "react-router-dom"; import { Menu,Icon } from 'antd'; const { SubMenu } = Menu; class System extends Component { componentDidMount() { } handleClick = e => { this.props.history.push(e.key) }; render() { ( <div> <header> 嵌套路由 </header> <Menu onClick={.handleClick} style={{ width: 256,float:'left' }} defaultSelectedKeys={['1']} defaultOpenKeys={['sub1']} mode="inline" > <SubMenu key="sub1" title={ <span> <Icon type="mail" /> <span>Navigation One</span> </span> } > <Menu.Item key="/system/bus">bus</Menu.Item> <Menu.Item key="/system/bus22">bus22</Menu.Item> </SubMenu> </Menu> <SystemRouter style={{ float:'left' }}/> </div> ); } } export default withRouter(System);
最后来俩效果图,页面分三部分,头部、左侧导航、右侧内容,切换时只有右侧内容变化。
原文链接:/react/868133.html