react-router 使用

本次使用react-router 版本为 5.0.1
本教程前提是你的应用程序是一个web应用程序,使用’react-router-dom‘包来实现页面的路由

在React router中有三种类型的组件,一是路由组件第二种是路径匹配组件第三种是导航组件
路由组件: BrowserRouter 和 HashRouter 
路径匹配的组件: Route 和 Switch 
导航组件: Link

安装

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 属性来定义路径是不是精确匹配。

使用url传参数

<Route path='/hello/:name' render={({match}) => {
            return <div>hello {match.params.name}</div>
  }} />

使用 <Route> 匹配的react 组件会在props 中包含一个match 的属性,通过match.params可以获取到参数对象

调用方法跳转

 <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中的方法

  1. history.push(url) 路由跳转
  2. hisroty.replace(url) 路由跳转不计入历史记录
  3. history.go(n) 根据索引前进或者后退
  4. history.goBack() 后端
  5. history.goForward() 前进

常用组件介绍

BrowserRouter

使用HTML5历史记录API(pushState,replaceState和popstate事件)的<Router>,以使您的UI与URL保持同步。

属性:

1.basename: string 如果你的项目在服务器上的一个子目录那么这个basename就是目录的名称例如/calendar

<BrowserRouter basename="/calendar" />
<Link to="/today"/> // renders <a href="/calendar/today">

2.getUserConfirmation

结合<Prompt> 组件使用可以拦截和修改 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

主要职责是当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 的话为区分大小写。

Link

导航到指定的路由

属性:

1.to:string|object
如果值为字符串,则导航到字符串所在的路由
object:

  • pathname :表示链接到的路径的字符串 /hello
  • search :query参数 ?name=cfl
  • hash : hash的值 #weixin
  • state

Switch

呈现于于location.pathname 所匹配的第一个 <Route> 或<Redirect>。

Prompt

当从当前路由退出的时候给一个提示框。


参阅文档

posted @ 2020-02-03 21:52  tianyamoon  阅读(396)  评论(0编辑  收藏  举报