<BrowserRouter>
<BrowserRouter>
使用 HTML5 提供的 history API (pushState
, replaceState
和 popstate
事件) 來保持 UI 和 URL 的同步。
import { BrowserRouter } from 'react-router-dom';
<BrowserRouter
basename={string}
forceRefresh={bool}
getUserConfirmation={func}
keyLength={number}
>
<App />
</BrowserRouter>
basename: string
所有位置的基準 URL。如果你的應用程序部署在服務器的子目錄,則需要將其設置為子目錄。basename
的正確格式是前面有一個前導斜杠,但不能有尾部斜杠。
<BrowserRouter basename="/calendar">
<Link to="/today" />
</BrowserRouter>
上例中的 <Link>
最終將被呈現為:
<a href="/calendar/today" />
forceRefresh: bool
如果為 true
,在導航的過程中整個頁面將會刷新。一般情況下,只有在不支持 HTML5 history API 的瀏覽器中使用此功能。
const supportsHistory = 'pushState' in window.history;
<BrowserRouter forceRefresh={!supportsHistory} />
getUserConfirmation: func
用于確認導航的函數,默認使用 window.confirm。例如,當從 /a
導航至 /b
時,會使用默認的 confirm
函數彈出一個提示,用戶點擊確定后才進行導航,否則不做任何處理。譯注:需要配合 <Prompt>
一起使用。
// 這是默認的確認函數
const getConfirmation = (message, callback) => {
const allowTransition = window.confirm(message);
callback(allowTransition);
}
<BrowserRouter getUserConfirmation={getConfirmation} />
keyLength: number
location.key
的長度,默認為 6
。
<BrowserRouter keyLength={12} />
children: node
要呈現的單個子元素(組件)。
<HashRouter>
<HashRouter>
使用 URL 的 hash
部分(即 window.location.hash
)來保持 UI 和 URL 的同步。
import { HashRouter } from 'react-router-dom';
<HashRouter>
<App />
</HashRouter>
注意: 使用
hash
記錄導航歷史不支持location.key
和location.state
。在以前的版本中,我們視圖 shim 這種行為,但是仍有一些問題我們無法解決。任何依賴此行為的代碼或插件都將無法正常使用。由于該技術僅用于支持舊式(低版本)瀏覽器,因此對于一些新式瀏覽器,我們鼓勵你使用<BrowserHistory>
代替。
basename: string
所有位置的基準 URL。basename
的正確格式是前面有一個前導斜杠,但不能有尾部斜杠。
<HashRouter basename="/calendar">
<Link to="/today" />
</HashRouter>
上例中的 <Link>
最終將被呈現為:
<a href="#/calendar/today" />
getUserConfirmation: func
用于確認導航的函數,默認使用 window.confirm。
// 這是默認的確認函數
const getConfirmation = (message, callback) => {
const allowTransition = window.confirm(message);
callback(allowTransition);
}
<HashRouter getUserConfirmation={getConfirmation} />
hashType: string
window.location.hash
使用的 hash
類型,有如下幾種:
-
slash
- 后面跟一個斜杠,例如 #/ 和 #/sunshine/lollipops -
noslash
- 后面沒有斜杠,例如 # 和 #sunshine/lollipops -
hashbang
- Google 風格的 ajax crawlable,例如 #!/ 和 #!/sunshine/lollipops
默認為 slash
。
children: node
要呈現的單個子元素(組件)。
<Link>
為你的應用提供聲明式的、可訪問的導航鏈接。
import { Link } from 'react-router-dom';
<Link to="/about">About</Link>
to: string
一個字符串形式的鏈接地址,通過 pathname
、search
和 hash
屬性創建。
<Link to='/courses?sort=name' />
to: object
一個對象形式的鏈接地址,可以具有以下任何屬性:
-
pathname
- 要鏈接到的路徑 -
search
- 查詢參數 -
hash
- URL 中的 hash,例如 #the-hash -
state
- 存儲到 location 中的額外狀態數據
<Link to={{
pathname: '/courses',
search: '?sort=name',
hash: '#the-hash',
state: {
fromDashboard: true
}
}} />
replace: bool
當設置為 true
時,點擊鏈接后將替換歷史堆棧中的當前條目,而不是添加新條目。默認為 false
。
<Link to="/courses" replace />
innerRef: func
允許訪問組件的底層引用。
const refCallback = node => {
// node 指向最終掛載的 DOM 元素,在卸載時為 null
}
<Link to="/" innerRef={refCallback} />
others
你還可以傳遞一些其它屬性,例如 title
、id
或 className
等。
<Link to="/" className="nav" title="a title">About</Link>
<NavLink>
一個特殊版本的 <Link>
,它會在與當前 URL 匹配時為其呈現元素添加樣式屬性。
import { NavLink } from 'react-router-dom';
<NavLink to="/about">About</NavLink>
activeClassName: string
當元素處于激活狀態時應用的類,默認為 active
。它將與 className
屬性一起使用。
<NavLink to="/faq" activeClassName="selected">FAQs</NavLink>
activeStyle: object
當元素處于激活狀態時應用的樣式。
const activeStyle = {
fontWeight: 'bold',
color: 'red'
};
<NavLink to="/faq" activeStyle={activeStyle}>FAQs</NavLink>
exact: bool
如果為 true
,則只有在位置完全匹配時才應用激活類/樣式。
<NavLink exact to="/profile">Profile</NavLink>
strict: bool
如果為 true
,則在確定位置是否與當前 URL 匹配時,將考慮位置的路徑名后面的斜杠。有關更多信息,請參閱 <Route strict> 文檔。
<NavLink strict to="/events/">Events</NavLink>
isActive: func
添加額外邏輯以確定鏈接是否處于激活狀態的函數。如果你要做的不僅僅是驗證鏈接的路徑名與當前 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>
location: object
isActive
默認比較當前歷史位置(通常是當前的瀏覽器 URL)。你也可以傳遞一個不同的位置進行比較。
<Prompt>
用于在位置跳轉之前給予用戶一些確認信息。當你的應用程序進入一個應該阻止用戶導航的狀態時(比如表單只填寫了一半),彈出一個提示。
import { Prompt } from 'react-router-dom';
<Prompt
when={formIsHalfFilledOut}
message="你確定要離開當前頁面嗎?"
/>
message: string
當用戶試圖離開某個位置時彈出的提示信息。
<Prompt message="你確定要離開當前頁面嗎?" />
message: func
將在用戶試圖導航到下一個位置時調用。需要返回一個字符串以向用戶顯示提示,或者返回 true
以允許直接跳轉。
<Prompt message={location => {
const isApp = location.pathname.startsWith('/app');
return isApp ? `你確定要跳轉到${location.pathname}嗎?` : true;
}} />
譯注:上例中的
location
對象指的是下一個位置(即用戶想要跳轉到的位置)。你可以基于它包含的一些信息,判斷是否阻止導航,或者允許直接跳轉。
when: bool
在應用程序中,你可以始終渲染 <Prompt>
組件,并通過設置 when={true}
或 when={false}
以阻止或允許相應的導航,而不是根據某些條件來決定是否渲染 <Prompt>
組件。
譯注:
when
只有兩種情況,當它的值為true
時,會彈出提示信息。如果為false
則不會彈出。見阻止導航示例。
<Prompt when={true} message="你確定要離開當前頁面嗎?" />
<MemoryRouter>
將 URL 的歷史記錄保存在內存中的 <Router>
(不讀取或寫入地址欄)。在測試和非瀏覽器環境中很有用,例如 React Native。
import { MemoryRouter } from 'react-router-dom';
<MemoryRouter>
<App />
</MemoryRouter>
initialEntries: array
歷史堆棧中的一系列位置信息。這些可能是帶有 {pathname, search, hash, state}
的完整位置對象或簡單的字符串 URL。
<MemoryRouter
initialEntries={[ '/one', '/two', { pathname: '/three' } ]}
initialIndex={1}
>
<App/>
</MemoryRouter>
initialIndex: number
initialEntries
數組中的初始位置索引。
getUserConfirmation: func
用于確認導航的函數。當 <MemoryRouter>
直接與 <Prompt>
一起使用時,你必須使用此選項。
keyLength: number
location.key
的長度,默認為 6
。
children: node
要呈現的單個子元素(組件)。
<Redirect>
使用 <Redirect>
會導航到一個新的位置。新的位置將覆蓋歷史堆棧中的當前條目,例如服務器端重定向(HTTP 3xx)。
import { Route, Redirect } from 'react-router-dom';
<Route exact path="/" render={() => (
loggedIn ? (
<Redirect to="/dashboard" />
) : (
<PublicHomePage />
)
)} />
to: string
要重定向到的 URL,可以是 path-to-regexp 能夠理解的任何有效的 URL 路徑。所有要使用的 URL 參數必須由 from
提供。
<Redirect to="/somewhere/else" />
to: object
要重定向到的位置,其中 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
進行訪問。
push: bool
如果為 true
,重定向會將新的位置推入歷史記錄,而不是替換當前條目。
<Redirect push to="/somewhere/else" />
from: string
要從中進行重定向的路徑名,可以是 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>
exact: bool
完全匹配,相當于 Route.exact。
strict: bool
嚴格匹配,相當于 Route.strict。
<Route>
<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 render methods
使用 <Route>
渲染一些內容有以下三種方式:
在不同的情況下使用不同的方式。在指定的 <Route>
中,你應該只使用其中的一種。請參閱下面的解釋,了解為什么有三個選項。大多數情況下你會使用 component
。
Route props
三種渲染方式都將提供相同的三個路由屬性:
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: func
使用 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>
中同時使用兩者。
children: func
有時候不論 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: string
可以是 path-to-regexp 能夠理解的任何有效的 URL 路徑。
<Route path="/users/:id" component={User} />
沒有定義 path
的 <Route>
總是會被匹配。
exact: bool
如果為 true
,則只有在 path
完全匹配 location.pathname
時才匹配。
<Route exact path="/one" component={OneComponent} />
[圖片上傳失敗...(image-d86957-1526486128879)]
strict: bool
如果為 true
,則具有尾部斜杠的 path
僅與具有尾部斜杠的 location.pathname
匹配。當 location.pathname
中有附加的 URL 片段時,strict
就沒有效果了。
<Route strict path="/one/" component={OneComponent} />
[圖片上傳失敗...(image-4289b9-1526486128879)]
警告:可以使用
strict
來強制規定location.pathname
不能具有尾部斜杠,但是為了做到這一點,strict
和exact
必須都是true
。
[圖片上傳失敗...(image-e932c7-1526486128879)]
location: object
一般情況下,<Route>
嘗試將其 path
與當前歷史位置(通常是當前的瀏覽器 URL)進行匹配。但是,也可以傳遞具有不同路徑名的位置進行匹配。
當你需要將 <Route>
與當前歷史位置以外的 location
進行匹配時,此功能非常有用。如過渡動畫示例中所示。
如果一個 <Route>
被包含在一個 <Switch>
中,并且需要匹配的位置(或當前歷史位置)傳遞給了 <Switch>
,那么傳遞給 <Route>
的 location
將被 <Switch>
所使用的 location
覆蓋。
sensitive: bool
如果為 true
,進行匹配時將區分大小寫。
<Route sensitive path="/one" component={OneComponent} />
[圖片上傳失敗...(image-2be4d5-1526486128879)]
<Router>
所有 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>
history: object
用于導航的歷史記錄對象。
import createBrowserHistory from 'history/createBrowserHistory';
const customHistory = createBrowserHistory();
<Router history={customHistory} />
children: node
要呈現的單個子元素(組件)。
<Router>
<App />
</Router>
<StaticRouter>
一個永遠不會改變位置的 <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);
basename: string
所有位置的基準 URL。basename
的正確格式是前面有一個前導斜杠,但不能有尾部斜杠。
<StaticRouter basename="/calendar">
<Link to="/today" />
</StaticRouter>
上例中的 <Link>
最終將被呈現為:
<a href="/calendar/today" />
location: string
服務器收到的 URL,可能是 node server 上的 req.url
。
<StaticRouter location={req.url}>
<App />
</StaticRouter>
location: object
一個形如 {pathname, search, hash, state}
的位置對象。
<StaticRouter location={{ pathname: '/bubblegum' }}>
<App />
</StaticRouter>
context: object
一個普通的 JavaScript 對象。在渲染過程中,組件可以向對象添加屬性以存儲有關渲染的信息。
const context = {};
<StaticRouter context={context}>
<App />
</StaticRouter>
當一個 <Route>
匹配時,它將把 context 對象傳遞給呈現為 staticContext
的組件。查看服務器渲染指南以獲取有關如何自行完成此操作的更多信息。
渲染之后,可以使用這些屬性來配置服務器的響應。
if (context.status === '404') {
// ...
}
children: node
要呈現的單個子元素(組件)。
<Switch>
用于渲染與路徑匹配的第一個子 <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>
location: object
用于匹配子元素而不是當前歷史位置(通常是當前的瀏覽器 URL)的 location 對象。
children: node
所有 <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>