先说概念
react-router
: 实现了路由的核心功能
react-router-dom
: 基于react-router
,加入了在浏览器运行环境下的一些功能,例如:Link
组件,会渲染一个a
标签,Link组件源码a
标签行; BrowserRouter
和HashRouter
组件,前者使用pushState
和popState
事件构建路由,后者使用window.location.hash
和hashchange
事件构建路由。
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import './utils/initEnv'; // import App from './App'; import Routes from './router/router'; import * as serviceWorker from './serviceWorker'; ReactDOM.render( <Routes/>, document.getElementById('root') ); // If you want your app to work offline and load faster, you can change // unregister() to register() below. Note this comes with some pitfalls. // Learn more about service workers: https://bit.ly/CRA-PWA serviceWorker.unregister();
上路由文件
import React from 'react' import {Route,Switch,HashRouter} from 'react-router-dom'; import Home from '../views/Home'; import List from '../views/List'; import Detail from '../views/Detail'; const MyRoute=()=>{ return <HashRouter>{/*return不能少*/} <Switch>{/*只匹配一次*/} <Route exact path="/" component={Home}/> {/*路径为/时匹配首页*/} <Route path="/list" component={List}/> <Route path="/detail" component={Detail}/> </Switch> </HashRouter> } export default MyRoute;
会vue的朋友们肯定更喜欢父子路由的方式
你可以借助react-router-config 具体使用可以参考官网,我这里直接介绍下我的使用
1 import { renderRoutes } from 'react-router-config'; 2 import {HashRouter as Router,Link,Route,Redirect} from 'react-router-dom'; 3 const routes=[ 4 { 5 path:'/', 6 exact:true, 7 render:()=><Redirect from="/" to="/index" /> 8 }, 9 { 10 path:'/index', 11 component:FirstIndex 12 } 13 ...省略 14 ]; 15 16 render(){ 17 18 return( 19 <Router history= {customHistory}> 20 {renderRoutes(routes)} 21 </Router> 22 ) 23 }