安裝
npm i react-router-dom -S
導(dǎo)入路由需要的組件
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
【常用路由組件如下:】
- BrowserRouter as Router
瀏覽器路由 別名為Router - Link導(dǎo)航 to切換的頁面
- Route路由頁面--path對應(yīng)鏈接component對應(yīng)組件
- BrowserLink
帶active激活的class路由連接
簡單路由代碼
import React, { Component } from 'react';
import {BrowserRouter as Router,Route,Link} from 'react-router-dom'
// 導(dǎo)入子組件
class App extends Component {
render() {
return (
<div className="App" >
<Router>
<div> <Link to="/">首頁</Link> | <Link to="/about">關(guān)于</Link> </div>
<hr/>
<Route path="/" exact component={Home}></Route>
<Route path="/about" component={About}></Route>
</Router>
</div>
);
}
}
function Home(){
return (<h1>我是首頁</h1>);
}
function About(){
return (<h1>我是關(guān)于</h1>);
}
export default App;
路由的參數(shù)
- 步驟01:定義指令Link指令
<Link to="/produce/123">產(chǎn)品123</Link> <Link to="/produce/abc">產(chǎn)品abc</Link> - 步驟02:定義路由
<Route path='/produce/:id' component={Produce}></Route> - 步驟03:定義組件-獲取路由參數(shù)
function Produce({match}){ return (<h1>我是產(chǎn)品:{match.params.id}</h1>); }
[match 是組件默認(rèn)傳遞的參數(shù), match.paras 組件路由參數(shù)對象, 還有 history對象和location對象]
子路由
- 步驟01:導(dǎo)入NavLink
import {BrowserRouter as Router,Route,Link,NavLink} from 'react-router-dom' - 步驟02:定義指令NavLink
<NavLink to="/detail">詳情</NavLink> - 步驟03:定義主路由
<Route path="/detail" component={Detail}></Route> - 步驟04:編寫主路由
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)前匹配的主路由地址]
- 步驟05:編寫子路由
function Arg(){
return (<h1>我是Arg </h1>);
}
function Com(){
return (<h1>我是com</h1>);
}
404頁面配置和Switch組件
[Switch能讓匹配的路由唯一]
[定義404,要寫在最后]
[location 當(dāng)前的地址]
[pathname 地址欄的信息]
- 步驟01:導(dǎo)入Switch
import {BrowserRouter as Router,Route,Link,Switch,NavLink,Redirect} from 'react-router-dom' - 步驟02:定義路由
<Switch>
<Route path="/" exact component={Home}></Route>
<Route path="/about" component={About}></Route>
<Route path="/produce/:id" component={Produce}></Route>
<Route path="/detail" component={Detail}></Route>
<Route component={NoMatch}></Route>
</Switch>
- 步驟03:編寫404路由
function NoMatch({location}){ return (<h1>頁面沒有找到{location.pathname}</h1>); }
路由重定向
- 導(dǎo)入重定向組件Redirect
- 重新編寫主路由
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>);
}
路由組件的參數(shù)
-
history
goBack() 返回
goForward() 前進(jìn)
push('/') 切換跳轉(zhuǎn)
replace 跳轉(zhuǎn)不留歷史記錄
-
location 地址欄信息
pathname路徑
-
match
params路由參數(shù)
url 配置的地址
路由如何傳參
props