目的:一般组件的this.props上没有路由组件有的history,match,location属性,因此需要使用withRouter将普通组件进行包裹
//引入withRouter
import {withRouter} from 'react-router-dom'
//使用
export default withRouter(index)
import React, { Component } from 'react'
import {withRouter} from 'react-router-dom'
class index extends Component {
back=()=>{
this.props.history.goBack()
}
forward=()=>{
this.props.history.goForward()
}
go=()=>{
this.props.history.go(-2)
}
render() {
return (
<div>
<h1>我是头部组件</h1>
<button onClick={this.back}>返回</button>
<button onClick={this.forward}>前进</button>
<button onClick={this.go}>回退两步</button>
</div>
)
}
}
export default withRouter(index)
此时this.props上面存在路由组件的三个属性了