加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

React-使用装饰器

发布时间:2020-12-15 20:34:25 所属栏目:百科 来源:网络整理
导读:create-react-app默认不支持装饰器的,需要做以下配置。 打开?package.json ,可以看到eject。运行 npm run?eject?可以让由create-react-app创建的项目的配置项暴露出来。 { ... "scripts" : { ... "eject": "react-scripts eject" },... } 运行 npm run?eje

  create-react-app默认不支持装饰器的,需要做以下配置。

  打开?package.json ,可以看到eject。运行 npm run?eject?可以让由create-react-app创建的项目的配置项暴露出来。

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

运行 npm run?eject?

  此时,项目中多了一个config文件,并且各个配置文件已经暴露出来了。(运行npm run?eject之前,保证本地没有待提交到git的文件)

安装babel插件
  Babel >= 7.x

npm install --save-dev @babel/plugin-proposal-decorators

  [email?protected]

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"
    ]
  }

  [email?protected]

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

至此,就可以在项目中使用装饰器了

@MyContainer
class B extends Component{
  render(){
    return (
      <p>B组件</p>
    )
  }
}
export default B;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读