使用react 高阶组件withRouter

使用react 高阶组件withRouter
withRouter 是一个高阶组件,把 match,location,history 三个对象注入到组件的 props 中。这是一个非常实用的函数
react中经过路由渲染的组件才拥有路由参数,使用this.props.history.push(’/a’)跳转到对应路由的页面
一般都是使用withRouter函数调用

import React, { Component } from 'react'
import { withRouter } from 'react-router-dom'

class ApiServ extends Component {
  render() {
    return (
      <div>
        API
      </div>
    )
  }
}

export default withRouter(ApiServ)

react中有一种装饰器@的方法
create-react-app默认不支持装饰器的,需要做以下配置。
打开 package.json ,可以看到eject。运行 npm run eject 可以让由create-react-app创建的项目的配置项暴露出来(运行之前要保证本地没有待提交git的代码)

"scripts": {
	"eject": "react-scripts eject"
}

完成之后本地会多一个config的文件夹
在这里插入图片描述
安装babel插件

babel >= 7.x
npm install --save-dev @babel/plugin-proposal-decorators
babel@6.x
npm install --save-dev babel-plugin-transform-decorators-legacy

修改package.json文件的babel配置项
Babel >= 7.x

"babel": {
    "plugins": [
      ["@babel/plugin-proposal-decorators", { "legacy": true }]
    ],
    "presets": [
      "react-app"
    ]
 }

babel@6.x

"babel": {
    "plugins": [
      "transform-decorators-legacy"
    ],
    "presets": [
      "react-app"
    ]
}

下面就可以使用装饰圈@了

import React, { Component } from 'react'
import { withRouter } from 'react-router-dom'

@withRouter
class ApiServ extends Component {
  render() {
    return (
      <div>
        API
      </div>
    )
  }
}

export default ApiServ
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值