本次使用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>
}
}
复制代码