首页 > 编写react使用es6和webpack

编写react使用es6和webpack

问题描述

在使用react+webpack,使用es6语法发生错误

相关代码

import React from 'react'
import ReactDOM from 'react-dom'

class PostInfo extends React.Component {
  constructor(props) {
    super(props);
    // Manually bind this method to the component instance...
    // this.state = {showOptionsModal: false};
    // this.handleOptionsButtonClick = this.handleOptionsButtonClick.bind(this);
  }

  state = {showOptionsModal: false};
  handleOptionsButtonClick = (e) => {
    this.setState({showOptionsModal: !this.state.showOptionsModal});
  };

  render() {
    var text = this.state.showOptionsModal + "";
    return (
      <button onClick={this.handleOptionsButtonClick}>{text}</button>
    )
  }
}
ReactDOM.render(<PostInfo></PostInfo>, document.getElementById('example'));

错误信息

当使用webpack命令时

webpack相关配置

package.json:
{
  "name": "webpack",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "babel-core": "^6.9.1",
    "babel-loader": "^6.2.4",
    "babel-preset-es2015": "^6.9.0",
    "babel-preset-react": "^6.5.0",
    "jquery": "^3.0.0",
    "react": "^15.1.0",
    "react-dom": "^15.1.0"
  }
}

.babelrc:
{
    "presets": [
        "react",
        "es2015"
    ]
}

webpack.config.js:
var path = require('path');

module.exports = {
    entry: './src/index.js',
    output: {
        path: path.join(__dirname, '/build'),
        filename: 'bundle.js'
    },
    resolve: {
        extensions: ['', '.js', '.jsx']
    },
    module: {
        loaders: [
            { test: /\.js|jsx$/, exclude: /node_modules/,loader: "babel-loader" }
        ]
    }
}

发生错误情况

最近在学习react和webpack,享用到es6的语法。在学习的过程中想使用 getInitialState,看到例子中是在构造函数中进行初始化,而我想提出来。在es6中使用onClick方法是,方法内部会发生一个上下文的改变,所以不想使用bind(this),想使用=>语法来避免使用bind(this)

参考文章 https://babeljs.io/blog/2015/06/07/react-on-es6-plus
http://bbs.reactnative.cn/topic/15/react-react-native-%E7%9A%84es5-es6%E5%86%99%E6%B3%95%E5%AF%B9%E7%85%A7%E8%A1%A8/2


class 里是不带分号的

=====

另外,class 里的 class-properties 并不在你的 preset 里面,这个插件在 stage-1 这个 preset 中,配置后应该就不会报错了。

【热门文章】
【热门文章】