1.引入路由包
yarn add react-router react-router-dom
react-router:是基本的router包,里边函的内容较多,但是在网页开发中有很多用不到,现在的市面上的课程讲的基本都是这个包的教程。
react-router-dom:随着react生态环境的壮大,后出现的包,这个包比react-router包轻巧了很多。
注意:其实安装了react-router包就不用安装了react-router-dom包了,这里只是为了给大家一个提示,所以安装了两个包。在实际开发中,请根据需要进行安装。
2.设置路由配置文件
在src目录下新建一个Router/index.js文件用于管理路由,这里需要引入一些对应的组件,比如首页啊,关于我们页面啊之类的页面,还有路由包文件。react路由中的Switch和exact的使用
Router的history是必需的props
Switch表示只渲染第一个与当前地址匹配的<Route>
Route的props path为路径,component为路径对应的页面
exact属性表示精确匹配
import Page1 from '../container/Page1';
import Page2 from '../container/Page2';
import React from 'react';
import {Router,Route,Switch,Redirect} from 'react-router-dom';
import { createHashHistory } from "history";
const history = createHashHistory();
class RouterConfig extends React.Component{
render(){
return(
<Router history={history}>
<Switch>
<Route path='/' exact render={()=>(
<Redirect to='/Page1'/>
)}/>
<Route path='/Page1' component={Page1}/>
<Route path='/Page2' component={Page2}/>
</Switch>
</Router>
)
}
}
export default RouterConfig;
3.在入口文件引入路由配置文件
import RouterConfig from './router/index.js';
ReactDOM.render(<RouterConfig/>, document.getElementById('root'));
4.在各组件中使用路由
<ul className="menu">
<li><NavLink to='/Page1'>第一个页面</NavLink></li>
<li><NavLink to='/Page2'>第二个页面</NavLink></li>
</ul>