React-Router 是 React 项目中处理路由的库.
1. HashRouter
通过 hashchange 监听路由的变化, 通过 Windows.location.hash 赋值触发监听的变化.
本质是一个 react 中的 context 对象, 向下传参, 传递参数有三种:
1. location
有四个属性: state, pathname, search, hash
state: 可以用来在路由中传递参数
pathname: 指定路由
2. history
主要有两个方法:
push: 可以实现跳转路由
- // 传递对象
- this.props.history.push({
- pathname: url, state: xxx
- })
- // 传递路由
- this.props.history.push(url)
- 3.match
通过该字段可以知道当前组件的路由是否和地址栏中路由相同.
应用:
实现单击后菜单呈现选中状态
- import React, { Component } from 'react'
- import { Route, Link } from '../react-router-dom';
- export default function ({to, exact, ...REST}) {
- // 实现单击后链接呈现选中状态
- return (
- <Route
- path={to}
- exact={exact}
- children={(props) => {
- return <Link to={to} className={props.match ? 'active' : ''}>{REST.children}</Link>
- }}
- />
- )
- }
- 2.BrowserRouter
通过 onpopstate 事件监听通过点击前进后退 / 调用 back() 等方法的操作. 通过改写 pushState 方法, 监听页面中路由的变化.
其他和 HashChange 基本相同
3. Route
用于渲染指定路由的组件. children 属性时, 可以不指定路由.
用于匹配路由: path, exact
path: 指定路由
exact: 严格匹配
有三个属性用于渲染组件:
1. component
当 path 值匹配时, 渲染 component 中的组件
2.render
当 path 匹配时, 可以自定义渲染逻辑. 相当于 React 中的 render props 复用组件功能.
如: 受保护路由的实现.
- import React from 'react';
- import Route from '../react-router-dom/Route';
- import { Redirect } from '../react-router-dom';
- export default function({component:Component, ...REST}) {
- return (
- <Route {...REST}
- render={(props) => localStorage.getItem('login') ?
- <Component {...props} />
- : <Redirect to={{pathname: '/login', state: {from: props.location.pathname}}} />}
- />
- )
- }
- 3.children
无论路由是否匹配, 都会渲染.
如: 菜单的选中状态
- import React, { Component } from 'react'
- import { Route, Link } from '../react-router-dom';
- export default function ({to, exact, ...REST}) {
- // 实现单击后链接呈现选中状态
- return (
- <Route
- path={to}
- exact={exact}
- children={(props) => {
- return <Link to={to} className={props.match ? 'active' : ''}>{REST.children}</Link>
- }}
- />
- )
- }
- 4. Link
to 属性有两种参数形式
1. 对象类型
<Link to={{pathname: url, state: {xx:xx}}}/>
2. 字符串
- <Link to="/user">
- 5. Switch/Redirect
Switch(只匹配一个路由) 和 Redirect(前面的都不匹配时走这个路由) 配合使用.
重定向方式有两种:
1) 组件重定向: <Redirect />
2) 方法重定向 this.props.history.push()
6. withRouter
对于非 Route 加载的组件, 想要使用从 Route 中传递的 history,location,match 属性, 使用该方法.
其本质是个高阶组件.
- import React from 'react';
- import Route from './Route';
- export default function(WrappedComponent) {
- return (props) => <Route component={WrappedComponent} />
- }
- 7. Prompt
1. 属性
1. when
根据该属性进行路由的拦截. 当为 true 时, 弹出一个下 confirm 框.
2.message
用于显示拦截的信息, 本质是个函数.
2. 原理
基于 history.push() 和 history.block() 方法.
来源: http://www.bubuko.com/infodetail-3340409.html