实战 React 之掌握 react-router-dom 路由配置、跳转与传参

实战 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;
  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);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值