React路由(基础)

Router

1.安装routerreact

cnpm i react-router-dom -Snpm

2.在最顶层引入router(只有最顶层才须要Router,一个app只须要一个Router)bash

import { BrowserRouter as Router } from 'react-router-dom'
复制代码

或者babel

import { HashRouter as Router } from 'react-router-dom'
复制代码

3.Route建立react-router

用于根据path渲染,path属性是一个字符串,还有一个component,render方法,使用route组件渲染的组件,内部能够直接经过this.props去获取路由相关信息app

用Route组件渲染的组件,内部能够经过this.props去获取路由相关信息,好比history, match,location这些对象,最好的方式是在内部把console.log(this.props)dom

(1)component方法ui

组件会直接渲染,能够直接在Home组件中,经过this.props来获取到router的一些操做方法this

// 父组件
import { BrowserRouter as Router, Route } from 'react-router-dom'
<Router>
    <Route path='/home' component={Home} />
</Router>
复制代码
// 子组件
import React, { Component } from 'react'

export default class Home extends Component {
  render() {
    console.log(this.props)
    return (
      <div>
        主页
      </div>
    )
  }
}
复制代码

访问home页面 spa

打印this.props

(2)render(这种叫作renderProps中)

使用render自定义渲染,渲染的结果返回一个element或者component,这个render是一个方法,这个方法的参数就是router相关的一些props

注意:

这里必定得把props扩展传递到组件里,要否则,在组件里,就不能经过 this.props来获取到router的一些操做方法 及属性

// 父组件
import { BrowserRouter as Router, Route } from 'react-router-dom'
<Router>
    <Route path="/about" render={(props) => {
          return (
            <div>
              <h3>关于咱们</h3>
              <About {...props} />
            </div>
          )
        }} />
</Router>
复制代码
// 子组件
import React, { Component } from 'react'

export default class About extends Component {
  render() {
    console.log(this.props)
    return (
      <div>
        关于
      </div>
    )
  }
}
复制代码

访问about页面

4.Link(NavLink)

用于跳转,必须有一个to参数,to参数能够是一个字符串路径,也能够是一个对象,对象能够经过state来传递参数,this.props.history.push(这里和Link组件的to一致)

<Link to="/home">主页</Link>
<Link to="/about">关于</Link>
复制代码

5.exact属性

彻底匹配path的时候,才会渲染,若是有一丁点儿不匹配,就不会渲染

6.Redirect重定向

<Redirect to="/home" from="/" />
复制代码

7.Switch

只会匹配一个子组件,只要匹配到一个,就不会再往下匹配,因此,在配置路由的时候,可能须要注意一下顺序

<Switch>
    <Route />
</Switch>
复制代码

8.withRouter高阶组件(截持渲染)

用于没有经过Route渲染的任意组件的props上注入路由相关的props

Home是一个组件
export default withRouter(Home)
复制代码

9.装饰器模式

cnpm i babel-plugin-transform-decorators-legacy -D
复制代码
@withRouter
复制代码
相关文章
相关标签/搜索