Javascript React 中的类变量与 ES6

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48489792/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:08:21  来源:igfitidea点击:

Class variables in React with ES6

javascriptreactjsobjectd3.jsecmascript-6

提问by Omkar

This question might have been answered somewhere else, but before marking as duplicate, please help me with it. I am referring to the following codepen using react and d3: https://codepen.io/swizec/pen/oYNvpQ

这个问题可能在其他地方得到了回答,但在标记为重复之前,请帮助我。我指的是使用 react 和 d3 的以下代码笔:https://codepen.io/swizec/pen/oYNvpQ

However, I am not able to figure out how can this codepen work with variables declared inside the class without any keywords:

但是,我无法弄清楚这个代码笔如何处理没有任何关键字的类中声明的变量:

class Colors extends Component {
 colors = d3.schemeCategory20;
  width = d3.scaleBand()
            .domain(d3.range(20));

   ....
}

When I try to execute this code, I get the following error:

当我尝试执行此代码时,出现以下错误:

./app/components/D3IndentedTree/Chloreophath.js
Module build failed: SyntaxError: Unexpected token (13:11)

  11 | // Draws an entire color scale
  12 | class Colors extends Component {
> 13 |     colors = d3.schemeCategory20;
     |            ^
  14 |     width = d3.scaleBand()
  15 |         .domain(d3.range(20));
  16 | 

I am not able to figure out why am I getting this error. I understand that you cant declare variables/properties of class directly inside the class. But how come then the code pen is working?

我无法弄清楚为什么会出现此错误。我知道您不能直接在类中声明类的变量/属性。但是代码笔是怎么工作的呢?

Thanks in advance!

提前致谢!

Update: Adding the webpack.config.js file:

更新:添加 webpack.config.js 文件:

    var path = require('path');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    entry: './app/index.js',
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'index_bundle.js',
        publicPath: '/'
    },
    module: {
        rules: [
            { test: /\.(js)$/, use: 'babel-loader' },
            { test: /\.css$/, use: [ 'style-loader', 'css-loader'] },
            {
                test: /\.png$/,
               loader: "url-loader?limit=100000"
             },
             {
               test: /\.jpg$/,
               loader: "file-loader"
             },
             {
              test: /\.(woff|woff2)(\?v=\d+\.\d+\.\d+)?$/,
               loader: 'url-loader? limit=10000&mimetype=application/font-woff'
              },
              {
               test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
               loader: 'url-loader?limit=10000&mimetype=application/octet-stream'
              },
              {
               test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
               loader: 'file-loader'
               },
               {
               test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
               loader: 'url-loader?limit=10000&mimetype=image/svg+xml'
              }
        ]
    },
    plugins: [new HtmlWebpackPlugin({
        template: 'app/index.html'
    }),
    new webpack.ProvidePlugin({
        "React": "react",
      }),],
    devServer: {
        historyApiFallback: true
    }
};

回答by T.J. Crowder

But how come then the code pen is working?

但是代码笔是怎么工作的呢?

Because it's using a transpiler (in that case, Babel) that supports that syntax(which is currently a Stage 3 proposal, not a specified feature [yet], but is commonly supported by transpilers used with React code).

因为它使用支持该语法的转译器(在这种情况下,Babel)(目前是第 3 阶段的提案,[尚未] 指定功能,但通常由与 React 代码一起使用的转译器支持)。

You can see that it's transpiling with Babel because it says "(Babel)" next to "JS" in the JS pane's header:

您可以看到它正在使用 Babel 进行编译,因为它在 JS 窗格标题中的“JS”旁边写着“(Babel)”:

enter image description here

在此处输入图片说明

...and if you click the gear icon next to it, you'll see Babel selected as the "Preprocessor".

...如果你点击它旁边的齿轮图标,你会看到 Babel 被选为“预处理器”。

In this particular case, Babel takes this:

在这种特殊情况下,Babel 采取了以下措施:

class Colors extends Component {
  colors = d3.schemeCategory20;
  width = d3.scaleBand()
            .domain(d3.range(20));

   // ....
}

...and makes it as though it had been written like this:

...并使它好像是这样写的:

class Colors extends Component {
  constructor() {
    this.colors = d3.schemeCategory20;
    this.width = d3.scaleBand()
                   .domain(d3.range(20));
  }
  // ....
}

...(and then might well turn that into ES5-compliant code, depending on the transpiling settings).

...(然后很可能将其转换为符合 ES5 的代码,具体取决于转译设置)。