安裝
npm i react-router-dom -S
路由組件
BrowserRouter as Router瀏覽器路由 別名 Router
所有的路由內(nèi)容都應(yīng)該放在Router里面
HashRouter as Router 哈希路由
NavLink 帶active導(dǎo)航
-
to導(dǎo)航的地址
to="/"
exact必須精確匹配如果被選中默認(rèn)會有個
active的class
Link 導(dǎo)航
- to 切換的頁面
Router 路由頁面
path對應(yīng)的地址component={} 對應(yīng)的組件exact精確匹配
Switch 一次只顯示一個路由
<Switch>
<Route />
</Switch>
Redirect 路由跳轉(zhuǎn)
from 從
to 跳轉(zhuǎn)的地址
Prompt 退出提示
- message 提示文字
WithRouter
讓非路由組件具有 ``路由Props`
import {WithRouter} from 'react-router-dom'
class ToDo{}
export default WithRouter(ToDo)
包裝
constructor(props){
props
match.history.location
}
路由的參數(shù)
<NavLink to="/produce/123">
<Route path="/produce:id" component={Produce}>
function Produce({match}){match.params.id}
路由組件的props
history
go
goBack() 返回
goForward 前進(jìn)
push("/") 切換跳轉(zhuǎn)
replace 跳轉(zhuǎn)不留歷史記錄
location 地址欄信息
-
pathname路徑
match
params
路由參數(shù)url
配置的地址
子路由
導(dǎo)入Navlink
import {BrowserRouter as Router,Route,Link,NavLink} from 'react-router-dom'
01 定義指令 Link指令
<NavLink to="/detail">詳情</NavLink>
02 定義主路由
<Route path="/detail" component={Detail}></Route>
03 編寫主路由
function Detail({location,match}){
return (
<div>
<div><NavLink to={match.url+'/arg'}>參數(shù)</NavLink> |
<NavLink to={match.url+'/com'}>評論</NavLink> | </div>
<hr/>
<Route path={match.url+'/arg'} component={Arg}></Route>
<Route path={match.url+'/com'} component={Com}></Route>
</div>);
}
//match.url 獲取當(dāng)前匹配的主路由地址
04 編寫子路由
function Arg(){
return (<h1>我是Arg </h1>);
}
function Com(){
return (<h1>我是com</h1>);
}
路由404配置 與Switch
01 導(dǎo)入Switch
import {BrowserRouter as Router,Route,Link,Switch,NavLink,Redirect} from 'react-router-dom'n
02 定義路由
<Switch>
<Route component={NoMatch}></Route>
</Switch>
//定義404路由要寫到最后
03 編寫404路由
function NoMatch({location}){
return (<h1>頁面沒有找到{location.pathname}</h1>);
}
重定向
我們需要寫一個默認(rèn)的子路由,這個時候可用重定向
01 導(dǎo)入重定向
import {
BrowserRouter as Router,
Route,
Link,
Switch,
NavLink,
Redirect
} from 'react-router-dom'
重新編寫 主路由
function Detail({location,match}){
return (<div>
<div><NavLink to={match.url+'/arg'}>參數(shù)</NavLink> |
<NavLink to={match.url+'/com'}>評論</NavLink> | </div>
<hr/>
<Switch>
<Route path={match.url+'/arg'} component={Arg}></Route>
<Route path={match.url+'/com'} component={Com}></Route>
<Redirect from={match.url} to={match.url+'/arg'}/>
</Switch>
</div>);
}
//from 是可以省略的