在v4+中路由规则位于布局和 UI 本身之间,因为route本身也是一个组件,万物皆组件,所以我们要嵌套路由直接在组件里写就可以了
看代码,新建一个list.jsx,然后再建两个子组件mobile和pc
import React from "react"; import { BrowserRouter as Router, Switch, Route, NavLink } from "react-router-dom"; import Mobile from './lists/Mobile'; import Pc from './lists/Pc'; import './home.css'; export default class List extends React.Component { render() { return ( <Router> <div> <ul> <li><NavLink to="/list/app" activeClassName="selected">手机端</NavLink></li> <li><NavLink to="/list/pc" activeClassName="selected">PC端</NavLink></li> </ul> <hr /> <Switch> <Route strict path="/list/app" component={Mobile}/> <Route strict path="/list/pc" component={Pc}/> {/* <Route component={()=><div>子路由的404!</div>}/> */} </Switch> </div> </Router> ); } }
mobile
import React from 'react'; export default class Mobile extends React.Component { render() { return ( <div> 进入手机端 </div> ) } }
pc的代码
import React from 'react'; export default class Pc extends React.Component { render() { return ( <div> 加入电脑pc模式 </div> ) } }
看效果