语法错误:react项目中的意外标记

时间:2017-07-18 15:17:01

标签: javascript reactjs webpack

我是React的新手,并且正在尝试将materialui组件集成到示例项目中。我面临以下问题:

Module build failed: SyntaxError: ./app/Tabs.jsx: Unexpected token
     (9:8)

   7 |
   8 | export default class IconLabelTabs extends Component {
>  9 |   state = {
     |         ^
  10 |     index: 0,
  11 |   };
  12 |

我提到了几个博客并找到了

{
    test: /.jsx?$/,
    loader: 'babel-loader',
    exclude: /node_modules/,
    query: {
      presets: ['es2015', 'react']
    }
},

在webpack中但仍面临同样的错误。

2 个答案:

答案 0 :(得分:4)

很可能你错过了babel-plugin-transform-class-properties插件。

我通常会添加预设stage-0以便拥有所有这些好东西。

$ npm i -D babel-preset-stage-0

.babelrcwebpack加载程序中

"presets": [
    ["es2015", { "modules": false, "loose": true }],
    "react",
    "stage-0"
  ],

答案 1 :(得分:2)

您必须在Component的构造函数中初始化状态变量。在你的情况下:

<强> ./应用程序/ Tabs.jsx

export default class IconLabelTabs extends Component {

  constructor(props) {
        super(props);
        this.state = {index: 0};
  }
}