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