官方英文文檔 - https://reacttraining.com/rea...
版本 -v4.2.0
<BrowserRouter>
使用 HTML5 提供的 history API (pushState
, replaceState
和 popstate
事件) 來保持 UI 和 URL 的同步。html
import { BrowserRouter } from 'react-router-dom'; <BrowserRouter basename={string} forceRefresh={bool} getUserConfirmation={func} keyLength={number} > <App /> </BrowserRouter>
全部位置的基準 URL。若是你的應用程序部署在服務器的子目錄,則須要將其設置爲子目錄。basename
的正確格式是前面有一個前導斜槓,但不能有尾部斜槓。node
<BrowserRouter basename="/calendar"> <Link to="/today" /> </BrowserRouter>
上例中的 <Link>
最終將被呈現爲:react
<a href="/calendar/today" />
若是爲 true
,在導航的過程當中整個頁面將會刷新。通常狀況下,只有在不支持 HTML5 history API 的瀏覽器中使用此功能。git
const supportsHistory = 'pushState' in window.history; <BrowserRouter forceRefresh={!supportsHistory} />
用於確認導航的函數,默認使用 window.confirm。例如,當從 /a
導航至 /b
時,會使用默認的 confirm
函數彈出一個提示,用戶點擊肯定後才進行導航,不然不作任何處理。譯註:須要配合 <Prompt>
一塊兒使用。github
// 這是默認的確認函數 const getConfirmation = (message, callback) => { const allowTransition = window.confirm(message); callback(allowTransition); } <BrowserRouter getUserConfirmation={getConfirmation} />
location.key
的長度,默認爲 6
。web
<BrowserRouter keyLength={12} />
要呈現的單個子元素(組件)。ajax
<HashRouter>
使用 URL 的 hash
部分(即 window.location.hash
)來保持 UI 和 URL 的同步。npm
import { HashRouter } from 'react-router-dom'; <HashRouter> <App /> </HashRouter>
注意: 使用hash
記錄導航歷史不支持location.key
和location.state
。在之前的版本中,咱們視圖 shim 這種行爲,可是仍有一些問題咱們沒法解決。任何依賴此行爲的代碼或插件都將沒法正常使用。因爲該技術僅用於支持舊式(低版本)瀏覽器,所以對於一些新式瀏覽器,咱們鼓勵你使用<BrowserHistory>
代替。
全部位置的基準 URL。basename
的正確格式是前面有一個前導斜槓,但不能有尾部斜槓。react-native
<HashRouter basename="/calendar"> <Link to="/today" /> </HashRouter>
上例中的 <Link>
最終將被呈現爲:api
<a href="#/calendar/today" />
用於確認導航的函數,默認使用 window.confirm。
// 這是默認的確認函數 const getConfirmation = (message, callback) => { const allowTransition = window.confirm(message); callback(allowTransition); } <HashRouter getUserConfirmation={getConfirmation} />
window.location.hash
使用的 hash
類型,有以下幾種:
slash
- 後面跟一個斜槓,例如 #/ 和 #/sunshine/lollipopsnoslash
- 後面沒有斜槓,例如 # 和 #sunshine/lollipopshashbang
- Google 風格的 ajax crawlable,例如 #!/ 和 #!/sunshine/lollipops默認爲 slash
。
要呈現的單個子元素(組件)。
爲你的應用提供聲明式的、可訪問的導航連接。
import { Link } from 'react-router-dom'; <Link to="/about">About</Link>
一個字符串形式的連接地址,經過 pathname
、search
和 hash
屬性建立。
<Link to='/courses?sort=name' />
一個對象形式的連接地址,能夠具備如下任何屬性:
pathname
- 要連接到的路徑search
- 查詢參數hash
- URL 中的 hash,例如 #the-hashstate
- 存儲到 location 中的額外狀態數據<Link to={{ pathname: '/courses', search: '?sort=name', hash: '#the-hash', state: { fromDashboard: true } }} />
當設置爲 true
時,點擊連接後將替換歷史堆棧中的當前條目,而不是添加新條目。默認爲 false
。
<Link to="/courses" replace />
容許訪問組件的底層引用。
const refCallback = node => { // node 指向最終掛載的 DOM 元素,在卸載時爲 null } <Link to="/" innerRef={refCallback} />
你還能夠傳遞一些其它屬性,例如 title
、id
或 className
等。
<Link to="/" className="nav" title="a title">About</Link>
一個特殊版本的 <Link>
,它會在與當前 URL 匹配時爲其呈現元素添加樣式屬性。
import { NavLink } from 'react-router-dom'; <NavLink to="/about">About</NavLink>
當元素處於激活狀態時應用的類,默認爲 active
。它將與 className
屬性一塊兒使用。
<NavLink to="/faq" activeClassName="selected">FAQs</NavLink>
當元素處於激活狀態時應用的樣式。
const activeStyle = { fontWeight: 'bold', color: 'red' }; <NavLink to="/faq" activeStyle={activeStyle}>FAQs</NavLink>
若是爲 true
,則只有在位置徹底匹配時才應用激活類/樣式。
<NavLink exact to="/profile">Profile</NavLink>
若是爲 true
,則在肯定位置是否與當前 URL 匹配時,將考慮位置的路徑名後面的斜槓。有關更多信息,請參閱 <Route strict> 文檔。
<NavLink strict to="/events/">Events</NavLink>
添加額外邏輯以肯定連接是否處於激活狀態的函數。若是你要作的不只僅是驗證連接的路徑名與當前 URL 的路徑名相匹配,那麼應該使用它。
// 只有當事件 id 爲奇數時才考慮激活 const oddEvent = (match, location) => { if (!match) { return false; } const eventID = parseInt(match.params.eventID); return !isNaN(eventID) && eventID % 2 === 1; } <NavLink to="/events/123" isActive={oddEvent}>Event 123</NavLink>
isActive
默認比較當前歷史位置(一般是當前的瀏覽器 URL)。你也能夠傳遞一個不一樣的位置進行比較。
用於在位置跳轉以前給予用戶一些確認信息。當你的應用程序進入一個應該阻止用戶導航的狀態時(好比表單只填寫了一半),彈出一個提示。
import { Prompt } from 'react-router-dom'; <Prompt when={formIsHalfFilledOut} message="你肯定要離開當前頁面嗎?" />
當用戶試圖離開某個位置時彈出的提示信息。
<Prompt message="你肯定要離開當前頁面嗎?" />
將在用戶試圖導航到下一個位置時調用。須要返回一個字符串以向用戶顯示提示,或者返回 true
以容許直接跳轉。
<Prompt message={location => { const isApp = location.pathname.startsWith('/app'); return isApp ? `你肯定要跳轉到${location.pathname}嗎?` : true; }} />
譯註:上例中的
location
對象指的是下一個位置(即用戶想要跳轉到的位置)。你能夠基於它包含的一些信息,判斷是否阻止導航,或者容許直接跳轉。
在應用程序中,你能夠始終渲染 <Prompt>
組件,並經過設置 when={true}
或 when={false}
以阻止或容許相應的導航,而不是根據某些條件來決定是否渲染 <Prompt>
組件。
譯註:when
只有兩種狀況,當它的值爲true
時,會彈出提示信息。若是爲false
則不會彈出。見 阻止導航示例。
<Prompt when={true} message="你肯定要離開當前頁面嗎?" />
將 URL 的歷史記錄保存在內存中的 <Router>
(不讀取或寫入地址欄)。在測試和非瀏覽器環境中頗有用,例如 React Native。
import { MemoryRouter } from 'react-router-dom'; <MemoryRouter> <App /> </MemoryRouter>
歷史堆棧中的一系列位置信息。這些多是帶有 {pathname, search, hash, state}
的完整位置對象或簡單的字符串 URL。
<MemoryRouter initialEntries={[ '/one', '/two', { pathname: '/three' } ]} initialIndex={1} > <App/> </MemoryRouter>
initialEntries
數組中的初始位置索引。
用於確認導航的函數。當 <MemoryRouter>
直接與 <Prompt>
一塊兒使用時,你必須使用此選項。
location.key
的長度,默認爲 6
。
要呈現的單個子元素(組件)。
使用 <Redirect>
會導航到一個新的位置。新的位置將覆蓋歷史堆棧中的當前條目,例如服務器端重定向(HTTP 3xx)。
import { Route, Redirect } from 'react-router-dom'; <Route exact path="/" render={() => ( loggedIn ? ( <Redirect to="/dashboard" /> ) : ( <PublicHomePage /> ) )} />
要重定向到的 URL,能夠是 path-to-regexp 可以理解的任何有效的 URL 路徑。全部要使用的 URL 參數必須由 from
提供。
<Redirect to="/somewhere/else" />
要重定向到的位置,其中 pathname
能夠是 path-to-regexp 可以理解的任何有效的 URL 路徑。
<Redirect to={{ pathname: '/login', search: '?utm=your+face', state: { referrer: currentLocation } }} />
上例中的 state
對象能夠在重定向到的組件中經過 this.props.location.state
進行訪問。而 referrer
鍵(不是特殊名稱)將經過路徑名 /login
指向的登陸組件中的 this.props.location.state.referrer
進行訪問。
若是爲 true
,重定向會將新的位置推入歷史記錄,而不是替換當前條目。
<Redirect push to="/somewhere/else" />
要從中進行重定向的路徑名,能夠是 path-to-regexp 可以理解的任何有效的 URL 路徑。全部匹配的 URL 參數都會提供給 to
,必須包含在 to
中用到的全部參數,to
未使用的其它參數將被忽略。
只能在 <Switch>
組件內使用 <Redirect from>
,以匹配一個位置。有關更多細節,請參閱 <Switch children>。
<Switch> <Redirect from='/old-path' to='/new-path' /> <Route path='/new-path' component={Place} /> </Switch>
// 根據匹配參數進行重定向 <Switch> <Redirect from='/users/:id' to='/users/profile/:id' /> <Route path='/users/profile/:id' component={Profile} /> </Switch>
譯註:通過實踐,發現以上「根據匹配參數進行重定向」的示例存在bug,沒有效果。to
中的:id
並不會繼承from
中的:id
匹配的值,而是直接做爲字符串顯示到瀏覽器地址欄!!!
徹底匹配,至關於 Route.exact。
嚴格匹配,至關於 Route.strict。
<Route>
多是 React Router 中最重要的組件,它能夠幫助你理解和學習如何更好的使用 React Router。它最基本的職責是在其 path
屬性與某個 location 匹配時呈現一些 UI。
請考慮如下代碼:
import { BrowserRouter as Router, Route } from 'react-router-dom'; <Router> <div> <Route exact path="/" component={Home} /> <Route path="/news" component={News} /> </div> </Router>
若是應用程序的位置是 /
,那麼 UI 的層次結構將會是:
<div> <Home /> <!-- react-empty: 2 --> </div>
或者,若是應用程序的位置是 /news
,那麼 UI 的層次結構將會是:
<div> <!-- react-empty: 1 --> <News /> </div>
其中 react-empty
註釋只是 React 空渲染的實現細節。但對於咱們的目的而言,它是有啓發性的。路由始終在技術上被「渲染」,即便它的渲染爲空。只要應用程序的位置匹配 <Route>
的 path
,你的組件就會被渲染。
使用 <Route>
渲染一些內容有如下三種方式:
在不一樣的狀況下使用不一樣的方式。在指定的 <Route>
中,你應該只使用其中的一種。請參閱下面的解釋,瞭解爲何有三個選項。大多數狀況下你會使用 component
。
三種渲染方式都將提供相同的三個路由屬性:
指定只有當位置匹配時纔會渲染的 React 組件,該組件會接收 route props 做爲屬性。
const User = ({ match }) => { return <h1>Hello {match.params.username}!</h1> } <Route path="/user/:username" component={User} />
當你使用 component
(而不是 render
或 children
)時,Router 將根據指定的組件,使用 React.createElement
建立一個新的 React 元素。這意味着,若是你向 component
提供一個內聯函數,那麼每次渲染都會建立一個新組件。這將致使現有組件的卸載和新組件的安裝,而不是僅僅更新現有組件。當使用內聯函數進行內聯渲染時,請使用 render
或 children
(見下文)。
使用 render
能夠方便地進行內聯渲染和包裝,而無需進行上文解釋的沒必要要的組件重裝。
你能夠傳入一個函數,以在位置匹配時調用,而不是使用 component
建立一個新的 React 元素。render
渲染方式接收全部與 component
方式相同的 route props。
// 方便的內聯渲染 <Route path="/home" render={() => <div>Home</div>} /> // 包裝 const FadingRoute = ({ component: Component, ...rest }) => ( <Route {...rest} render={props => ( <FadeIn> <Component {...props} /> </FadeIn> )} /> ) <FadingRoute path="/cool" component={Something} />
警告:<Route component>
優先於<Route render>
,所以不要在同一個<Route>
中同時使用二者。
有時候不論 path
是否匹配位置,你都想渲染一些內容。在這種狀況下,你可使用 children
屬性。除了不管是否匹配它都會被調用之外,它的工做原理與 render
徹底同樣。
children
渲染方式接收全部與 component
和 render
方式相同的 route props,除非路由與 URL 不匹配,不匹配時 match
爲 null
。這容許你能夠根據路由是否匹配動態地調整用戶界面。以下所示,若是路由匹配,咱們將添加一個激活類:
const ListItemLink = ({ to, ...rest }) => ( <Route path={to} children={({ match }) => ( <li className={match ? 'active' : ''}> <Link to={to} {...rest} /> </li> )} /> ) <ul> <ListItemLink to="/somewhere" /> <ListItemLink to="/somewhere-else" /> </ul>
這對動畫也頗有用:
<Route children={({ match, ...rest }) => ( {/* Animate 將始終渲染,所以你能夠利用生命週期來爲其子元素添加進出動畫 */} <Animate> {match && <Something {...rest} />} </Animate> )} />
警告:<Route component>
和<Route render>
優先於<Route children>
,所以不要在同一個<Route>
中同時使用多個。
能夠是 path-to-regexp 可以理解的任何有效的 URL 路徑。
<Route path="/users/:id" component={User} />
沒有定義 path
的 <Route>
老是會被匹配。
若是爲 true
,則只有在 path
徹底匹配 location.pathname
時才匹配。
<Route exact path="/one" component={OneComponent} />
若是爲 true
,則具備尾部斜槓的 path
僅與具備尾部斜槓的 location.pathname
匹配。當 location.pathname
中有附加的 URL 片斷時,strict
就沒有效果了。
<Route strict path="/one/" component={OneComponent} />
警告:可使用strict
來強制規定location.pathname
不能具備尾部斜槓,可是爲了作到這一點,strict
和exact
必須都是true
。
通常狀況下,<Route>
嘗試將其 path
與當前歷史位置(一般是當前的瀏覽器 URL)進行匹配。可是,也能夠傳遞具備不一樣路徑名的位置進行匹配。
當你須要將 <Route>
與當前歷史位置之外的 location
進行匹配時,此功能很是有用。如過渡動畫示例中所示。
若是一個 <Route>
被包含在一個 <Switch>
中,而且須要匹配的位置(或當前歷史位置)傳遞給了 <Switch>
,那麼傳遞給 <Route>
的 location
將被 <Switch>
所使用的 location
覆蓋。
若是爲 true
,進行匹配時將區分大小寫。
<Route sensitive path="/one" component={OneComponent} />
全部 Router 組件的通用低階接口。一般狀況下,應用程序只會使用其中一個高階 Router:
使用低階 <Router> 的最多見用例是同步一個自定義歷史記錄與一個狀態管理庫,好比 Redux 或 Mobx。請注意,將 React Router 和狀態管理庫一塊兒使用並非必需的,它僅用於深度集成。
import { Router } from 'react-router-dom'; import createBrowserHistory from 'history/createBrowserHistory'; const history = createBrowserHistory(); <Router history={history}> <App /> </Router>
用於導航的歷史記錄對象。
import createBrowserHistory from 'history/createBrowserHistory'; const customHistory = createBrowserHistory(); <Router history={customHistory} />
要呈現的單個子元素(組件)。
<Router> <App /> </Router>
一個永遠不會改變位置的 <Router>
。
這在服務器端渲染場景中很是有用,由於用戶實際上沒有點擊,因此位置實際上並未發生變化。所以,名稱是 static
(靜態的)。當你只須要插入一個位置,並在渲染輸出上做出斷言以便進行簡單測試時,它也頗有用。
如下是一個示例,node server 爲 <Redirect>
發送 302 狀態碼,併爲其它請求發送常規 HTML:
import { createServer } from 'http'; import React from 'react'; import ReactDOMServer from 'react-dom/server'; import { StaticRouter } from 'react-router'; createServer((req, res) => { // 這個 context 對象包含了渲染的結果 const context = {}; const html = ReactDOMServer.renderToString( <StaticRouter location={req.url} context={context}> <App /> </StaticRouter> ); // 若是使用 <Redirect>,context.url 將包含要重定向到的 URL if (context.url) { res.writeHead(302, { Location: context.url }); res.end(); } else { res.write(html); res.end(); } }).listen(3000);
全部位置的基準 URL。basename
的正確格式是前面有一個前導斜槓,但不能有尾部斜槓。
<StaticRouter basename="/calendar"> <Link to="/today" /> </StaticRouter>
上例中的 <Link>
最終將被呈現爲:
<a href="/calendar/today" />
服務器收到的 URL,多是 node server 上的 req.url
。
<StaticRouter location={req.url}> <App /> </StaticRouter>
一個形如 {pathname, search, hash, state}
的位置對象。
<StaticRouter location={{ pathname: '/bubblegum' }}> <App /> </StaticRouter>
一個普通的 JavaScript 對象。在渲染過程當中,組件能夠向對象添加屬性以存儲有關渲染的信息。
const context = {}; <StaticRouter context={context}> <App /> </StaticRouter>
當一個 <Route>
匹配時,它將把 context 對象傳遞給呈現爲 staticContext
的組件。查看服務器渲染指南以獲取有關如何自行完成此操做的更多信息。
渲染以後,可使用這些屬性來配置服務器的響應。
if (context.status === '404') { // ... }
要呈現的單個子元素(組件)。
用於渲染與路徑匹配的第一個子 <Route>
或 <Redirect>
。
這與僅僅使用一系列 <Route>
有何不一樣?
<Switch>
只會渲染一個路由。相反,僅僅定義一系列 <Route>
時,每個與路徑匹配的 <Route>
都將包含在渲染範圍內。考慮以下代碼:
<Route path="/about" component={About} /> <Route path="/:user" component={User} /> <Route component={NoMatch} />
若是 URL 是 /about
,那麼 <About>
、<User>
和 <NoMatch>
將所有渲染,由於它們都與路徑匹配。這是經過設計,容許咱們以不少方式將 <Route>
組合成咱們的應用程序,例如側邊欄和麪包屑、引導標籤等。
可是,有時候咱們只想選擇一個 <Route>
來呈現。好比咱們在 URL 爲 /about
時不想匹配 /:user
(或者顯示咱們的 404 頁面),這該怎麼實現呢?如下就是如何使用 <Switch>
作到這一點:
import { Switch, Route } from 'react-router'; <Switch> <Route exact path="/" component={Home} /> <Route path="/about" component={About} /> <Route path="/:user" component={User} /> <Route component={NoMatch} /> </Switch>
如今,當咱們在 /about
路徑時,<Switch>
將開始尋找匹配的 <Route>
。咱們知道,<Route path="/about" />
將會被正確匹配,這時 <Switch>
會中止查找匹配項並當即呈現 <About>
。一樣,若是咱們在 /michael
路徑時,那麼 <User>
會呈現。
這對於動畫轉換也頗有用,由於匹配的 <Route>
與前一個渲染位置相同。
<Fade> <Switch> {/* 這裏只會渲染一個子元素 */} <Route /> <Route /> </Switch> </Fade> <Fade> <Route /> <Route /> {/* 這裏老是會渲染兩個子元素,也有多是空渲染,這使得轉換更加麻煩 */} </Fade>
用於匹配子元素而不是當前歷史位置(一般是當前的瀏覽器 URL)的 location 對象。
全部 <Switch>
的子元素都應該是 <Route>
或 <Redirect>
。只有第一個匹配當前路徑的子元素將被呈現。
<Route>
組件使用 path
屬性進行匹配,而 <Redirect>
組件使用它們的 from
屬性進行匹配。沒有 path
屬性的 <Route>
或者沒有 from
屬性的 <Redirect>
將始終與當前路徑匹配。
當在 <Switch>
中包含 <Redirect>
時,你可使用任何 <Route>
擁有的路徑匹配屬性:path
、exact
和 strict
。from
只是 path
的別名。
若是給 <Switch>
提供一個 location
屬性,它將覆蓋匹配的子元素上的 location
屬性。
<Switch> <Route exact path="/" component={Home} /> <Route path="/users" component={Users} /> <Redirect from="/accounts" to="/users" /> <Route component={NoMatch} /> </Switch>