实战 React 之掌握 react-router-dom 路由配置、跳转与传参
本文所述的 react-router-dom 版本为 5.0.0;react-router 版本为 5.0.0。
一、react-router-dom 路由配置
import React from 'react';
import {HashRouter, BrowserRouter,Route,Redirect,Switch,Link,NavLink} from 'react-router-dom';
import Home from './component/home';
import Detail from './component/detail';
const Router = () => (
<BrowserRouter>
<Route exact path="/" component={Home}/>
<Route path="/detail" name="detail" component={Detail}/>
</BrowserRouter>
);
export default Router;
- 路由配置属性主要有 path、name、component 等。
path:组件相对路径
name:组件路径别名
component:组件地址 - 在路由配置中,有两个属性 exact 和 strict 表示路径匹配。
“/detail” exact 属性为 true 时匹配的路由有:"/detail/",
但是 url 中有 “/detail/” 匹配不到。
“/detail” strict 属性为 true 时匹配的路由有:"/detail",
但是 “/detail/” 可以被匹配到。
综上所述,要想严格匹配,就需要将 exact 和 strict 都设为 true
二、react-router-dom 路由跳转
路由跳转有两种方式。
- link 或者 NavLink形式,实质是个 a 标签。区别是后者可以切换时改变样式,用法如下:
<ul>
<li><NavLink exact to="/" activeStyle={{
fontWeight: 'bold',
color: 'red'
}}>home</NavLink>
</li>
<li><NavLink exact to="/detail" activeStyle={{
fontWeight: 'bold',
color: 'red'
}}>detail</NavLink>
</li>
</ul>
- 直接使用点击事件,用法如下:
<ul>
<li onClick={() => this.props.history.push({pathname:'detail'})}><div>home</div>
</li>
<li onClick={() => this.props.history.push({pathname:'home'})}><div>detail</div>
</li>
</ul>
三、react-router-dom 路由传参
上面有提到两种路由跳转方式,相应的路由传参也有两种方式。
- 组件跳转传参
<ul>
<li><NavLink exact to="/" activeStyle={{
fontWeight: 'bold',
color: 'red'
}}>home</NavLink>
</li>
<li><NavLink exact to={{pathname:'detail',state:{id:2}}} activeStyle={{
fontWeight: 'bold',
color: 'red'
}}>detail</NavLink>
</li>
</ul>
使用 NavLink 进行配置,使用 to 属性进行跳转和传参。
- 事件跳转传参
<ul>
<li onClick={() => this.props.history.push({pathname:'detail',state:{id:1}})}><div>home</div>
</li>
<li onClick={() => this.props.history.push({pathname:'home',state:{
id:0}})}><div>detail</div>
</li>
</ul>
- 获取参数
constructor(props){
super(props);
console.log(this.props.history.location.state);
}