介绍
使用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() 返回上一级
* */