目录
一、介绍
1、作用:路由是根据不同的url地址展示不同的页面或者内容
2、安装
(1)官网安装:http://reacttraining.com/react-router/web/guides/quick-start
(2)终端安装:
npm install react-router-dom@5
二、使用
1、导入
//引入 import {HashRouter, Router} from 'react-router-dom'
2、定义路由
render(){ return ( <div> <HashRouter> <Router path="/home" component={Home} /> <Router path="/second" component={Second} /> <Router path="/mine" component={Mine} /> </HashRouter> </div> ) }
建议:将路由单独封装在一个js文件中
注意:一级路由与多级路由
3、重定向
作用:如果我们不想让用户访问某个路由或者该路由不在我们书写的路由中,我们可以让组件跳转到我们指定的路由
{/模糊匹配 重定向*/} {/*<Redirect from="/" to="/home" exact />*/} {/*exact 精确地*/} <Redirect path="*" component={Test} />
4、嵌套路由
(1)父组件
<Route path="/home" component={Home}>
(2)子组件Home:直接使用Route
<Route path="/home/page1" component={Page1} /> <Route path="/home/page2" component={Page2} /> <Redirect from='/home' to='home/page1' />
5、路由跳转
(1)声明式路由
<NavLink to="/home" activeClassHome="ok">home</NavLink> <NavLink to="/second" activeClassHome="ok">second</NavLink> <NavLink to="/mine" activeClassHome="ok">mine</NavLink>
(2)编程式路由
<1>this.props.history.push(路由)
<2> props.history.push(路由)
import {useHistory} from 'react-router-dom' const history = useHistory() history.push(路由)
6、路由传参
(1)使用params参数
const in