本次使用react-router 版本爲 5.0.1 本教程前提是你的應用程序是一個web應用程序,使用’react-router-dom‘包來實現頁面的路由css
在React router中有三種類型的組件,一是路由組件
第二種是路徑匹配組件
第三種是導航組件
。 路由組件: BrowserRouter
和 HashRouter
路徑匹配的組件: Route
和 Switch
導航組件: Link
html
npm install react-router-dom
複製代碼
import React from 'react'
import TodoList from './components/TodoList'
import { BrowserRouter as Router, Route, Link } from 'react-router-dom'
import './App.css'
const App: React.FC = () => {
return (
<div className='App'>
<Router>
<Link to='/'>root</Link> <br />
<Link to='/hello'>hello</Link> <br />
<Link to='/todolist'>todolist</Link>
<div>
<Route path='/' exact render={() => {
return <div>root page</div>
}} />
<Route path='/hello' render={() => {
return <div>hello world</div>
}} />
<Route path='/todolist' component={TodoList} />
</div>
</Router>
</div>
)
}
export default App
複製代碼
經過上面的代碼我麼就實現了咱們項目的基本路由功能,Router
組件決定了咱們使用html5 history api,Route
組件定義了路由的匹配規則和渲染內容,使用 Link
組件進行路由之間的導航。使用 exact
屬性來定義路徑是否是精確匹配。html5
<Route path='/hello/:name' render={({match}) => {
return <div>hello {match.params.name}</div>
}} />
複製代碼
使用 <Route>
匹配的react 組件會在props 中包含一個match
的屬性,經過match.params
能夠獲取到參數對象node
<Route path='/hello/:name' render={({ match, history }) => {
return <div>
hello {match.params.name}
<button onClick={()=>{
history.push('/hello')
}}>to hello</button>
</div>
}} />
複製代碼
使用 <Route>
匹配的react 組件會在props 中包含一個history
的屬性,history中的方法react
使用HTML5歷史記錄API(pushState,replaceState和popstate事件)的,以使您的UI與URL保持同步。web
屬性:npm
1.basename: string 若是你的項目在服務器上的一個子目錄那麼這個basename就是目錄的名稱例如/calendar
後端
<BrowserRouter basename="/calendar" />
<Link to="/today"/> // renders <a href="/calendar/today">
複製代碼
2.getUserConfirmationapi
結合 組件使用能夠攔截和修改 Prompt 的消息。數組
function getConfirmation(message, callback) {
const allowTransition = window.confirm(message);
callback(allowTransition);
}
<BrowserRouter getUserConfirmation={getConfirmation} />;
複製代碼
3.forceRefresh:bool 若是爲true在頁面導航的時候後採用整個頁面刷新的形式。 4.keyLength location.key(表示當前位置的惟一字符串)的長度。默認爲6。 5.children:node 要渲染的子元素。
主要職責是當Route的位置和路徑匹配的時候渲染對應的ui
屬性:
用於渲染的props
1.component 一個react 組件,將在path
匹配的時候自動渲染
2.render:func 經過編寫一個方法,方法返回一個react dom ,當 path匹配的時候自動渲染
3.children:func 一樣是一個方法,匹配規則時不管path是否匹配都會渲染,可是match屬性只有在路由匹配的時候纔會有值。這樣方便你根據路由是否匹配渲染不一樣的ui
<Route path='/hello' exact children={({ match, history, location }) => {
return <div>
hello {match ? 'match' : ''}
</div>
}}></Route>
複製代碼
上面的三種方法都能在組件中獲取到route傳過去的三個props history / location / match
其餘屬性:
4.path:string | string[] 須要匹配的路徑或者路徑數組
5.exact:bool 若是爲true,則僅在路徑與location.pathname徹底匹配時才匹配。
6.strict 若是爲true,則具備尾部斜槓的路徑將僅匹配具備尾部斜槓的location.pathname。當location.pathname中有其餘URL段時,這不起做用。
7.sensitive:bool 匹配規則對大小寫是否敏感,true 的話爲區分大小寫。
導航到指定的路由
屬性:
1.to:string|object 若是值爲字符串,則導航到字符串所在的路由 object:
/hello
?name=cfl
#weixin
呈現於於location.pathname 所匹配的第一個 或。
當從當前路由退出的時候給一個提示框。
class TestComp extends React.Component {
render() {
return <div>
<Prompt message='test' when={true}></Prompt>
test router
</div>
}
}
複製代碼