目录
引入
项目引入
直接引入
页面栈
基本使用
BrowserRouter(Router)
Switch
Link
Route
path
component
render
exact
children
Redirect
from|to
Prompt
when
message
代码跳转链接
路由传参
withRouter()
示例
match
isExact
params
path
url
location
hash
pathname
search
state
history
length
action
push
replace
go
goBack
goForward
block
v5到v6区别
react路由文档
npm install react-router-dom --save
当发生路由切换的时候,页面栈的表现如下:
属性 |
类型 |
---|---|
初始化 |
新页面入栈 |
打开新页面 |
新页面入栈 |
页面重定向 |
当前页面出栈,新页面入栈 |
页面返回 |
页面不断出栈,直到目标返回页 |
Tab 切换 |
页面全部出栈,只留下新的 Tab 页面 |
重加载 |
页面全部出栈,只留下新的页面 |
下面例子默认只显示one和two,当点击one或two时,下面会对应显示one或two。点击third时会重定向到one。点击other时,显示no match。
import React, { Component } from 'react'
import { Link, BrowserRouter as Router, Switch, Route, Redirect } from 'react-router-dom'
function RouteOne() {
return one
}
function RouteTwo() {
return two
}
export default class testR extends Component {
render() {
return (
-
one
-
two
-
third
-
other
two
}>
no match
}>
)
}
}
管理所有路由系统。下面的标签都必须写在Router标签内。只能有一个子元素。
路由自动切换组件,相当于vue中的router-view。没有匹配到路径不会有任何显示。
路由跳转,是router中的“超链接”,相当于vue中router-link,点击会跳转to属性对应的链接。
存储组件和路径的对应关系。
路由组件的路径和Link的to属性对应。没有path属性时,对应的是没有匹配的路径,此时会显示该Route对应的内容。
path路径下对应显示的组件(组件需要继承了react.Component)。使用方式component={组件名}。
和component属性之间只能有一个,对应一个函数,返回的内容为path路径下对应显示的内容。例如:render={(routerProps)=>
用于精准匹配时,Route的路径匹配模式默认是模糊匹配,即path=‘/first’会匹配到任何以/first开头的路径。
对应一个函数(和render相同),接收同样的参数,但是不管路径是否匹配到返回的内容都会被渲染,没匹配到时routerProps.match属性为undefined。
路由重定向组件。
当跳转到from对应的链接时,重定向到to对应的链接。
确认框组件。在跳转前弹出提示框提示是否要跳转过去。
当为true时,跳转前才会弹出提示框。
提示框中的提示文字。
只有通过组件注入路由相关的值后才能使用,this.props.history.push('/first'),此时url链接在后面拼接/first。相当于vue中的this.$router.push('/first')。
默认在Route组件的render属性对应的函数中会接收一个参数,该参数里面有路由信息,可以在其中拿到参数。
向组件的props中注入路由相关的值 (history、location、match属性)。Route中传入占位符,Link跳转链接中拼接对应参数,这样便会添加到对应的match的params属性下。
下面有2种获取参数的方法,一个是render属性的函数中对应的参数,一个通过withRouter注入对应类组件的this.props。
import React, { Component } from 'react'
import { Link, BrowserRouter as Router, Switch, Route, withRouter } from 'react-router-dom'
class RouteOne extends Component {
render(){
console.log(this.props)
const { name, age } = this.props.match.params
return {name} is {age}
}
}
withRouter(RouteOne)
export default class testR extends Component {
render() {
return (
-
one
-
two
{
console.log(routerProps)
return two
}}>
)
}
}
下面是routerProps打印的对象的属性。
携带匹配结果及url参数
是否设置了严格匹配。
路由携带参数。
Route中定义的path路径(通常和url相同,带参数时不同)。
当前的实际路径。
当前实际路径的解析结果。
哈希值。例如localhost:3000/blog/index?id=1#title,哈希值为#title
完整的路径,例如localhost:3000/blog/index?id=1#title,路径为/blog/index。
url中的搜索语句,例如localhost:3000/blog/index?id=1#title,搜索语句为?id=1。
页面跳转传递的参数。
入栈的历史记录数量。
当前栈动作(PUSH|REPLACE|POP)
新记录入栈,push(path,[state])接收2个参数,一个是路径,一个是页面跳转参数为可选的。
替换当前的记录,replace(path,[state])接收2个参数,一个是路径,一个是页面跳转参数为可选的。
在栈中将指针移动n个位置,go(number)。当前位置为0.
等价于go(-1),一般相当于回退操作。
等价于go(1),一般相当于前进操作。
组织路由跳转,类似与Prompt组件,block(message)。调用会产生一个提示框,message为提示框显示的文本,取消会不跳转。
解读《React Router从v5到v6》 - 知乎
Introduction | React Router 中文文档