您的位置:首页 > Web前端 > React

实战 React 第2天:掌握 react-router-dom 路由配置、跳转与传参

2019-06-04 15:02 731 查看
版权声明:本文为回眸一笑原创作品,欢迎关注「前端集锦」公众号。 https://blog.csdn.net/weixin_44135121/article/details/90767640

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;
  1. 路由配置属性主要有 path、name、component 等。
    path:组件相对路径
    name:组件路径别名
    component:组件地址
  2. 在路由配置中,有两个属性 exact 和 strict 表示路径匹配。
    “/detail” exact 属性为 true 时匹配的路由有:"/detail/",
    但是 url 中有 “/detail/” 匹配不到。
    “/detail” strict 属性为 true 时匹配的路由有:"/detail",
    但是 “/detail/” 可以被匹配到。
    综上所述,要想严格匹配,就需要将 exact 和 strict 都设为 true

二、react-router-dom 路由跳转

路由跳转有两种方式。

  1. 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>
  1. 直接使用点击事件,用法如下:
<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 路由传参

上面有提到两种路由跳转方式,相应的路由传参也有两种方式。

  1. 组件跳转传参
<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 属性进行跳转和传参。

  1. 事件跳转传参
<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>
  1. 获取参数
constructor(props){
super(props);
console.log(this.props.history.location.state);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: