简体   繁体   English

JavaScript ES6语法是什么?

[英]What is this JavaScript ES6 syntax?

Learning React, and I'm looking over Google's MaterialUI docs, and it shows a syntax that looks like: 学习React,我正在查看Google的MaterialUI文档,它显示的语法如下:

export default class DialogExampleModal extends React.Component {
  state = {
    open: false,
  };

  handleOpen = () => {
    this.setState({open: true});
  };
...

Babel with es2015 is failing on the state= part of this code: 使用es2015的Babel在此代码的state =部分失败:

ERROR in ./client/App.jsx
Module build failed: SyntaxError: Unexpected token (23:8)

  21 |   }
  22 | 
> 23 |   state = {
     |         ^
  24 |     open: false,
  25 |   };
  26 | 

My question is, what is this syntax and do I have something possibly configured wrong? 我的问题是,这是什么语法,我是否可能将某些配置错误? It seems that other ES2015 syntax works fine. 看来其他ES2015语法也可以正常工作。

I think you either need to set class' properties inside the constructor like this: 我认为您需要像这样在构造函数中设置类的属性:

export default class DialogExampleModal extends React.Component {

  constructor() {
    this.state = {
      open: false,
    };

    this.handleOpen = () => {
      this.setState({open: true});
    };
  }

}

or you can use transform-class-properties babel plugin, to make code from your question compile. 或者,您可以使用transform-class-properties babel插件,从问题中编译代码。

Well, the first thing that jumps out to me is that the sample code has an open brace before the state code and yours has a closing bracket. 好吧,让我惊讶的第一件事是示例代码在状态代码之前有一个大括号,而您的代码有一个右括号。

export default class DialogExampleModal extends React.Component { // HERE
  state = { // HERE
    open: false,
  };

  handleOpen = () => {
    this.setState({open: true});
  };

And yours: 你的呢:

  21 |   } // HERE
  22 | 
> 23 |   state = {

If you are closing the component before the state function, it will throw an error because it is an undefined function it isn't expecting outside the component. 如果要在状态函数之前关闭组件,则它将抛出错误,因为这是一个未定义的函数,它在组件外部并不期望。

If that is another function inside the component, you need a semicolon after it. 如果那是组件内部的另一个函数,则需要在其后加上分号。

  21 |   }; // SEMICOLON HERE
  22 | 
> 23 |   state = {

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM