React-router-dom
API
<BrowserRoute>
<Router> 使用 HTML5 提供的 history API (pushState, replaceState 和 popstate 事件) 來保持 UI 和 URL 的同步叫搁。
- basename: string
- 當前位置的基準URL吁伺。如果你的頁面部署在服務器的二級(子)目錄,你需要將 basename 設置到此子目錄。 正確的 URL 格式是前面有一個前導斜杠量蕊,但不能有尾部斜杠剑刑。
<HashRouter>
HashRouter 使用 URL 的 hash (例如:window.location.hash) 來保持 UI 和 URL 的同步风题。
<Router>
- 當存在服務區(qū)來管理動態(tài)請求時骚腥,需要使用
<BrowserRouter>
組件,而<HashRouter>
被用于靜態(tài)網站 - 所有路由器組件的通用接口,使用時
<Router>
標簽只能包含一個子標簽担忧,一般Router
放在元素標簽最頂部,只需使用包括- <BrowserRouter>
- <HashRouter>
<Route path='/roster'/>
// 當路徑名為'/'時, path不匹配
// 當路徑名為'/roster'或'/roster/2'時, path匹配
// 當你只想匹配'/roster'時坯癣,你需要使用"exact"參數(shù)
// 則路由僅匹配'/roster'而不會匹配'/roster/2'
<Route exact path='/roster'/>
<Route>
渲染
當匹配到對應的路徑時瓶盛,呈現(xiàn)相應的頁面
-
Route
渲染頁面的三種方法- component :一個React組件。當帶有component參數(shù)的route匹配成功后示罗,route會返回一個新的元素惩猫,其為component參數(shù)所對應的React組件(使用React.createElement創(chuàng)建)
<Route path='/page' component={Page} />
- render : 一個返回React element的函數(shù)。當匹配成功后調用該函數(shù)蚜点。該過程與傳入component參數(shù)類似轧房,并且對于行級渲染與需要向元素傳入額外參數(shù)的操作會更有用。
<Route path='/page' render={(props) => ( <Page {...props} data={extraProps}/> )}/>
- children : 一個返回React element的函數(shù)绍绘。與上述兩個參數(shù)不同奶镶,無論route是否匹配當前l(fā)ocation,其都會被渲染
<Route path='/page' children={(props) => ( props.match ? <Page {...props}/> : <EmptyPage {...props}/> )}/>
嵌套路由
/roster?:對應路徑名僅僅是/roster時陪拘,因此需要在exact元素上添加exact參數(shù)厂镇。
/roster/:number?:?該路由使用一個路由參數(shù)來獲取/roster后的路徑名。
<Switch>
<Route exact path='/roster' component={FullRoster}/>
<Route path='/roster/:number' component={Player}/>
</Switch>
路徑參數(shù)
- 如'/roster/:number'中:number這種寫法意味著/roster/后的路徑名將會被獲取并存在
match.params.number
中左刽。例如捺信,路徑名'/roster/6'會獲取到一個對象:
const Player = (props) => {
const number = props.match.params.number;
return (
<div>
<h1>參數(shù):{number}</h1>
</div>
)
<Link>
提供路由跳轉和導航,顯示在html中就是a標簽
- to: string
- 需要跳轉到的路徑(pathname)或地址(location)
- to: object
- 需要跳轉到的地址(location)
- replace: bool
- 默認為false
- 當設置為 true 時欠痴,點擊鏈接后將使用新地址替換掉訪問歷史記錄里面的原地址
- 當設置為 false 時迄靠,點擊鏈接后將在原有訪問歷史記錄的基礎上添加一個新的紀錄秒咨。
<NavLink>
特殊版本的<Link>
,當需要設置導航點擊,匹配當前路由樣式時梨水,使用該組件
- activeClassName:string
- 設置匹配當前路由時的a標簽類名拭荤,默認類名是
class='active'
- 設置匹配當前路由時的a標簽類名拭荤,默認類名是
- activeStyle: object
- 設置匹配當前路由時的a標簽樣式
- exact: bool
- 默認是
false
,設置為true
則只有完全匹配時才能應用activeClassName
和activeStyle
- 默認是
<Switch>
History
Location
JS控制路由跳轉及傳參
this.props.history.push({
pathname: '/order-detail',//路由
state: {
orderNo: params //傳參
},
});
//接受參數(shù)
let orderNo = this.props.location.state.orderNo