目前前端项目都是SPA项目,而单页应用就少不了路由配置,因为单页应用的页面不会刷新页面,而是根据路由的切换来更换页面组件内容的显示。参考网址
1.引入路由包
npm install --save react-router react-router-dom
react-router
:是基本的router
包,里边函的内容较多,但是在网页开发中有很多用不到,现在的市面上的课程讲的基本都是这个包的教程。
react-router-dom
:随着react
生态环境的壮大,后出现的包,这个包比react-router
包轻巧了很多。`
注意:其实安装了react-router
包就不用安装了react-router-dom
包了,这里只是为了给大家一个提示,所以安装了两个包。在实际开发中,请根据需要进行安装。安装时使用--save
,因为这是要在生产环境中使用的。
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>