• 在dva脚手架或create-react-app脚手架组合中使用装饰器


    最近做react项目的时候,使用的是create-react-app脚手架搭建的项目,用的ant-design框架,在使用UI框架的Form组件的时候,发现 Form.create 方法是一个典型的装饰器,于是就改成装饰器的写法
     
     
    dav框架

    1、先安装包 
    yarn add @babel/plugin-proposal-decorators --save

    2、将.webpackrc  改成.webpackrc.js然后具体配置

    const config = {};
    //用于跨域
    config.proxy = {
      "/api": {
        "target": "http://localhost:7001",
        "changeOrigin": true,
        "pathRewrite": {
          "^/api": ""
        }
      }
    }
    //antd按需加载引入
    config.extraBabelPlugins = [
      ["import", {
        "libraryName": "antd",
        "libraryDirectory": "es",
        "style": "css"
      }],
      //装饰器语法配置
      [
        "@babel/plugin-proposal-decorators",
        {
          "legacy": true
        }
      ]
    ]
    
    
    
    export default config;

    在 creat-react-app创建的脚手架配置

    1、先安装包 

    yarn add @babel/plugin-proposal-decorators --save

    2、在项目根目录下创建.babelrc, config-overrides.js文件

    {
        "presets": [
            "react-app"
        ],
        "plugins": [
            [
                "import",
                {
                    "libraryName": "antd",
                    "libraryDirectory": "es",
                    "style": "css" // `style: true` 会加载 less 文件
                }
            ],
            [
                "@babel/plugin-proposal-decorators",
                {
                    "legacy": true
                }
            ]
        ]
    }

    3、删除package.json的babel配置

    // 删除下面几行
    "babel": {
        "presets": [
          "react-app"
        ]
      },

    这样我们就可以使用装饰器语法了

    装饰器 语法使用之前  拿antd的包为例子

    // const WrappedNormalLoginForm = Form.create({ name: 'normal_login' })(Login);

    // export default WrappedNormalLoginForm;        抛出的是这个改变后的变量  而不是Login这个组件了
     
    使用后
     
    @Form.create({ name: 'normal_login' })     注意这里不要加分号  放在class上面
     
    export default Login
  • 相关阅读:
    git this exceeds GitHub's file size limit of 100.00 MB
    使用vue-cli创建vue工程
    【转】Visual Studio Code必备插件
    linux安装openssl
    Centos7离线安装mysql8
    使用nmon来按频率采集数据
    Mac下编译android4.0.4遇到的问题
    32位ubuntu16.4编译android4.1.1
    vmvare安装vmtools菜单灰色
    Substrate 使用
  • 原文地址:https://www.cnblogs.com/p-123/p/11385144.html
Copyright © 2020-2023  润新知