react-route-dom

介绍

使用React构建应用时,需要使用路由实现页面跳转。在React中,常用react-router-dom包实现路由跳转。
本文主要针对react-router-dom进行说明

安装

首先进入项目目录,使用npm安装react-router-dom: npm install react-router -S

引用

import React, { Component } from "react";
import {
  BrowserRouter,
  HashRouter, 
  Route,
  Link,
  Switch,
  Redirect,
  NavLink,
} from "react-router-dom";

说明

BrowserRouter, // 一个使用了 HTML5 history API 的高阶路由组件,保证你的 UI 界面和 URL 保持同步
  HashRouter, //使用 URL 的 hash 部分(即 window.location.hash)来保持 UI 和 URL 的同步
  Route, // 路由标签,用来声明标签路径和组件
  Link,
  /*
  <Link to="/about" replace exact strict>About</Link>
  to:{
    pathname,  要链接到的路径
    state:{     存储到 location 中的额外状态数据
        id:xx
    }
  }
  replace: 当设置为 true 时,点击链接后将替换历史堆栈中的当前条目,而不是添加新条目。默认为 false
  exact: 如果为 true,则只有在位置完全匹配时才应用激活类/样式
  strict: 如果为 true,则在确定位置是否与当前 URL 匹配时,将考虑位置的路径名后面的斜杠
  */
  Switch,
  /*
  * 用于渲染与路径匹配的第一个子 <Route> 或 <Redirect>
  * */
  Redirect, // 重定向标签,用来处理路径错误时需要跳转到的页面,如首页
  NavLink,
  /*
  * 一个特殊版本的 <Link>,它会在与当前 URL 匹配时为其呈现元素添加样式属性
  * */

路由传参

/*
  * 路由跳转
  * 1.显式传参
  * 路由定义 <Route exact path="/detail/:id" component={Detail}/>  页面 this.props.match.params获取
  * 2.隐式传参
  * onClick={() => this.props.history.push({
                        pathname: '/detail',
                        state: {
                            id: 3
                        })
  * this.props.history.location.state 获取
  *
  * 跳转方式
  * this.props.history.push
  * this.props.history.replace 防止出现死循环
  * this.props.history.goBack() 返回上一级
  * */
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值