将一般组件拥有路由组件身上的api(使用withRouter)

  1. 一般组件经过withRouter的加工,也有了路由组件history身上特有的那些api
  2. withRouter专门用于在一般组件身上使用路由组件的问题
  3. withRouter的返回值是一个新组件
import React, {
    
     Component } from 'react'
import {
    
    withRouter} from 'react-router-dom'
class Header extends Component {
    
    
    back=()=>{
    
    
        this.props.history.goBack()
    }
    forward=()=>{
    
    
        this.props.history.goForward()
    }

    go=()=>{
    
    
        this.props.history.go(-2)
    }
    render() {
    
    
        console.log('Header组件收到的props是:',this.props)
        return (
            <div className="page-header">
                <h2>React Router Demo</h2>
                <button onClick={
    
    this.back}>回退</button>
                <button onClick={
    
    this.forward}>前进</button>
                <button onClick={
    
    this.go}>go</button>
            </div>
        )
    }
}
export default  withRouter(Header)

猜你喜欢

转载自blog.csdn.net/weixin_48952990/article/details/126618009
今日推荐