ES7 装饰器模式的配置

装饰器模式简介

在使用 React 框架编程中,我们用高阶组件的时候,使用时往往需要用高阶组件函数包裹当前组件来导出的形式,过于麻烦。装饰器模式则优化了这一点,让我们在编程的过程中节省一点精力。

当我们使用了装饰器模式,React 中的高阶组件就可以这样来使用:

装饰器的使用

装饰器模式的配置
  • 安装依赖

    cnpm i @babel/plugin-proposal-decorators react-scripts @babel/plugin-syntax-jsx @babel/helper-create-regexp-features-plugin -D

  • 修改 package.json 文件中的 babel 配置项

      "babel": {
        "plugins": [
          ["@babel/plugin-proposal-decorators", { "legacy": true}]
        ]
      }
    
  • 在 src 目录下的 config-overrides.js 文件的配置项中增加以下内容

    addDecoratorsLegacy()
    
  • 在根目录下创建 jsconfig.json 文件,配置以下内容

    让编译器对装饰器写法不出警告

    {
        "compilerOptions": {
            "experimentalDecorators": true
        }
    }
    
注意一些踩坑点
  1. 不允许在装饰器和类之间使用export关键字!!!

    比如这样(错误示范):

    import React, { Component } from 'react'
    import layoutHoc from '@layout'
    
    // 错误行为!!!装饰器和类名之间不能使用export!!!
    @layoutHoc
    export default class Home extends Component {
        render() {
            return (
                <div>Home</div>
            )
        }
    }
    

    ↑ 报错:Parsing error: Using the export keyword between a decorator and a class is not allowed. Please use export @dec class instead.

    我们可以改成这样子(正确示范):

    import React, { Component } from 'react'
    import layoutHoc from '@layout'
    
    // 好习惯
    @layoutHoc
    class Home extends Component {
        render() {
            return (
                <div>Home</div>
            )
        }
    }
    
    export default Home;
    
  2. 装饰器不能用来装饰函数组件!!!

    错误示范:

    import React, { Component } from 'react'
    import layoutHoc from '@layout'
    
    // 装饰符必须加到类的声明前!!!
    @layoutHoc
    function home(){
        return (
            <div>Home</div>
        )
    }
    export default home;
    

    ↑ 报错:Parsing error: Leading decorators must be attached to a class declaration

    所以这时候要用类组件来编写啦

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值