react-router非常復(fù)雜整體瀑志,比vue-router強大很多雀鹃,好好研究坞笙,對你自身能力提高很有幫助
1. 安裝
cnpm install react-router --save 包含react router核心
cnpm install react-router-dom --save 包含react router的dom綁定
2. BrowserRouter
BrowserRouter是react路由的容器
相關(guān)屬性如下
basename闷供,用來設(shè)置路由的基礎(chǔ)鏈接仍稀,<BrowserRouter basename="/api" />
getUserConfirmation拳芙,用來攔截Prompt組件察藐,并且決定是否跳轉(zhuǎn),我專門做了一個例子
forceRefresh舟扎,用來設(shè)置是否強制瀏覽器整體刷新分飞,默認是false
keLength,用來設(shè)置location.key的長度睹限,默認是6譬猫,可以自定義
注意讯檐,BrowserRouter只能有一個子節(jié)點
3. BrowserRouter屬性getUserConfirmation的使用例子
由于默認是用的window.confirm做驗證,很丑染服,可以自己定義
使用必須導(dǎo)入Prompt這個組件是用來傳遞確認信息的
import React from 'react'
import ReactDOM from 'react-dom'
import { Prompt } from 'react-router'
import {
BrowserRouter as Router,
Route,
Link
} from 'react-router-dom'
const MyComponent1 = () => (
<div>組件一</div>
)
const MyComponent2 = () => (
<div>組件二</div>
)
class MyComponent extends React.Component {
render() {
const getConfirmation = (message,callback) => {
const ConFirmComponent = () => (
<div>
{message}
<button onClick={() => {callback(true);ReactDOM.unmountComponentAtNode(document.getElementById('root1'))}}>確定</button>
<button onClick={() => {callback(false);ReactDOM.unmountComponentAtNode(document.getElementById('root1'))}}>取消</button>
</div>
)
ReactDOM.render(
<ConFirmComponent />,
document.getElementById('root1')
)
}
return (
<Router getUserConfirmation={getConfirmation}>
<div>
<Prompt message="Are you sure you want to leave?" />
<Link to="/a">跳轉(zhuǎn)組件二</Link>
<Route component={MyComponent1}/>
<Route exact path="/a" component={MyComponent2}/>
</div>
</Router>
)
}
}
ReactDOM.render(
<MyComponent/>,
document.getElementById('root')
)
4. HashRouter
别洪,這個是用來兼容老瀏覽器的,略
5. Link
Link的作用和a標(biāo)簽類似
屬性
to
接受path字符串柳刮,<Link to="/a" />
接受對象
<Link to={{
pathname: '/courses', // 傳遞的pathname
search: '?sort=name', // 傳遞的url參數(shù)
hash: '#the-hash', // 在url參數(shù)后面的hash值
state: { fromDashboard: true } // 自定義屬性存在location中
}}/>
replace挖垛,設(shè)置為true,會取代當(dāng)前歷史記錄
6. NavLink
NavLink和Link一樣最終都是渲染成a標(biāo)簽秉颗,NavLink可以給這個a標(biāo)簽添加額外的屬性
<NavLink to="/a">組件一</NavLink> 當(dāng)點擊此路由晕换,a標(biāo)簽?zāi)J添加一個名為active的class
屬性
activeClassName 用于自定義激活a標(biāo)簽的class
activeStyle 用于設(shè)置激活a標(biāo)簽的樣式
activeStyle={{
fontWeight: 'bold',
color: 'red'
}}
exact,當(dāng)路徑百分百匹配的時候才展示樣式和class站宗,但是不影響路由的匹配闸准,"/a"和"/a/" 是相等的
strict,這個比exact還很梢灭,就算 "/a"和"/a/" 也是不相等的
isActive夷家,此屬性接收一個回調(diào)函數(shù),用來做跳轉(zhuǎn)的最后攔截
<NavLink isActive={oddEvent} to="/a/123">組件一</NavLink>
const oddEvent = (match, location) => {
console.log(match,location)
if (!match) {
return false
}
console.log(match.id)
return true
}
match里面保存了路由匹配信息的參數(shù)敏释,是動態(tài)化的
location里面保存的Link中的to傳遞的所有信息
location库快,此參數(shù)用來接受一個location對象,如果對象信息和當(dāng)前的location信息對象匹配則跳轉(zhuǎn)
<NavLink to="/a/123" location={{key:"mb5wu3",pathname:"/a/123"}}/>
7. Prompt
Prompt是用來提示用戶是否要跳轉(zhuǎn)钥顽,給用戶提示信息默認使用window.confirm义屏,可以結(jié)合getUserConfirmation構(gòu)建自定義提示信息
import { Prompt } from 'react-router'
屬性
message
傳遞字符串,用于提示用戶的展示信息
傳遞函數(shù)蜂大,可以接受location對象作為參數(shù)
<Prompt message={location => {
console.log(location);
return true
}}/>
return true表示可以直接跳轉(zhuǎn)闽铐,無需驗證
return '你好'表示要給提示給用戶的信息
when,接受一個布爾值奶浦,表示是否執(zhí)行prompt
8. MemoryRouter
主要用于native端兄墅,路由歷史不通過URL緩存,而是保存在內(nèi)存中
也就是說澳叉,地址欄地址不變隙咸,而在內(nèi)存中保存路由信息,當(dāng)瀏覽器刷新時成洗,自動跳回路由首頁
還是可以通過訪問location對象得到路由信息
import { MemoryRouter } from 'react-router'
屬性
initialEntries 一個數(shù)組用來傳遞路由的初始匹配值
<MemoryRouter initialEntries={["/a","/b"]}>...</MemoryRouter>
數(shù)組成員可以是字符串也可以是location對象五督,成員的默認順序是最左邊的展示出來
initialIndex 用來確定initialEntries數(shù)組展示路由的索引
<MemoryRouter initialIndex={1} initialEntries={["/a","/b"]}>...</MemoryRouter>
getUserConfirmation 和上面講的一樣
keyLength 也是用來設(shè)置location.key的長度的
9. Redirect
路由重定向
import { Redirect } from 'react-router'
使用這個 <Redirect to="/a" /> 代替組件使用
屬性
to
字符串,要重定向的路徑
對象瓶殃,location對象
push充包,布爾值,是否將當(dāng)前路徑存到history中(是Link標(biāo)簽的to路徑)
from碌燕,用來指定路由的原始值误证,如果不是給定的字符串继薛,那么不渲染,反之渲染愈捅,只能用于switch組件中
10. Route
Route的作用就是用來渲染路由匹配的組件
路由渲染有三種方式遏考,每一種方式都可以傳遞match,location,history對象
component
用來渲染組件
<Route path="/a" component={MyComponent1}></Route>
render
用來渲染函數(shù)式組件,可以防止重復(fù)渲染組件
<Route path="/b" render={({match,location,history}) => {
console.log(match,location,history);
return <div>組件二</div>
}}></Route>
children
和render差不多蓝谨,不過可以用來動態(tài)的展示組件
差別之處在于灌具,children會在路徑不匹配的時候也調(diào)用回調(diào)從而渲染函數(shù),而render只會在路徑匹配的時候觸發(fā)回調(diào)
<Route path="/b" children={({match,location,history}) => {
return (
match ? <div>組件二</div>:<div>組件二二</div>
)
}}></Route>
屬性
path譬巫,字符串咖楣,匹配的路徑
exact,布爾值芦昔,路徑完全匹配的時候跳轉(zhuǎn) "/a/"和"/a"是一樣的
strict诱贿,布爾值咕缎,單獨使用和沒有使用這個屬性沒有任何區(qū)別焙蹭,如果和exact一起使用可以構(gòu)建更為精確的匹配模式。"/a/"和"/a"是不同的
location孔厉,傳遞route對象,和當(dāng)前的route對象對比刊驴,如果匹配則跳轉(zhuǎn)舅柜,如果不匹配則不跳轉(zhuǎn)。另外绍载,如果route包含在swicth組件中,如果route的location和switch的location匹配阳谍,那么route的location會被switch的location替代
11. Router
低級路由吊洼,適用于任何路由組件旺订,主要和redux深度集成意乓,使用必須配合history對象
使用Router路由的目的是和狀態(tài)管理庫如redux中的history同步對接
關(guān)于history插件的使用請看 http://www.cnblogs.com/ye-hcj/p/7741742.html
import { Router } from 'react-router'
import { createBrowserHistory } from 'history/createBrowserHistory'
const history = createBrowserHistory();
<Router history={history}>
...
</Router>
12. StaticRouter,
靜態(tài)路由,主要用于服務(wù)端渲染爪模,暫不涉及
13. Switch
Switch組件內(nèi)部可以是Route或者Redirect应狱,只會渲染第一個匹配的元素
屬性
location
Switch可以傳遞一個location對象,路由匹配將和這個location對象進行比較污朽,而不是url
Route元素會比較path炎功,Redirect會比較from坛怪,如果他們沒有對應(yīng)的屬性,那么就直接匹配
14. history
這里的history對象是使用history插件生成的,http://www.cnblogs.com/ye-hcj/p/7741742.html已經(jīng)詳細講過了
記住一點义锥,再使用location做對比的使用,通過history訪問的location是動態(tài)變化的岩灭,最好通過Route訪問location
15. location
location對象表示當(dāng)前的路由位置信息噪径,主要包含如下屬性
{
hash: undefined,
key: "k9r4i3",
pathname: "/c",
state: undefined,
search: ""
}
16. match
match對象表示當(dāng)前的路由地址是怎么跳轉(zhuǎn)過來的,包含的屬性如下
{
isExact: true, // 表示匹配到當(dāng)前路徑是否是完全匹配
params: {}, // 表示路徑的動態(tài)參數(shù)值
path: '/c', // 匹配到的原始路徑
url: '/c' // 匹配到的實際路徑
}
17. matchPath
matchPath也是和后端相關(guān)的,主要作用就是生成一個match對象
import { matchPath } from 'react-router'
const match = matchPath('/a/123',{
path: '/a/:id',
exact: true,
strict: false
})
第一個參數(shù)是pathname
第二個參數(shù)是一個對象薄料,里面的屬性和route的屬性類似谷市,用來和pathname做對比
如果匹配的話蛔垢,就產(chǎn)生一個match對象,反之迫悠,null
18. withRouter
當(dāng)一個非路由組件也想訪問到當(dāng)前路由的match,location,history對象艺玲,那么withRouter將是一個非常好的選擇
import { withRouter } from 'react-router'
const MyComponent = (props) => {
const { match, location, history } = this.props
return (
<div>{props.location.pathname}</div>
)
}
const FirstTest = withRouter(MyComponent)
參考文檔:
react-router