组件定义中的Babel语法错误起反应

时间:2016-06-07 12:33:38

标签: reactjs ecmascript-6 babeljs

我只是遵循了这些解释:https://babeljs.io/blog/2015/06/07/react-on-es6-plus

提到的地方:

// The ES6+ way
class Video extends React.Component {
  static defaultProps = {
    autoPlay: false,
    maxLoops: 10,
  }
  static propTypes = {
    autoPlay: React.PropTypes.bool.isRequired,
    maxLoops: React.PropTypes.number.isRequired,
    posterFrameSrc: React.PropTypes.string.isRequired,
    videoSrc: React.PropTypes.string.isRequired,
  }
  state = {
    loopsRemaining: this.props.maxLoops,
  }
}

但如果我这样做:

class AddUserGeolocation extends React.Component {

  static propTypes = {
    alreadyAsked: React.PropTypes.bool.isRequired
  }

  componentDidMount {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition((position) => {
        dispatcher(addUser('You', position.coords.latitude, position.coords.longitude))
      });
      dispatcher(askedForUserLocation())
    }
  };

  render() {
    let result = this.props.alreadyAsked ? 'Asked' : 'Not yet'
    return (
      <div>
        {result}
      </div>
    )
  }
}

我明白了:

ERROR in ./js/containers/AddUserGeolocation.js
Module build failed: SyntaxError: /home/augustin/Workspace/myapp/js/containers/AddUserGeolocation.js: Unexpected token (13:19)
  11 | class AddUserGeolocation extends React.Component {
  12 | 
> 13 |   static propTypes = {
     |                    ^
  14 |     alreadyAsked: React.PropTypes.bool.isRequired
  15 |   }
  16 | 

这里有什么问题?

我对ES6,ES7,ES2015,Babel等感到困惑......

使用:

dependencies": {
    "express": "^4.13.4",
    "babel-polyfill": "^6.3.14",
    "react": "^0.14.7",
    "react-dom": "^0.14.7",
    "react-redux": "^4.1.2",
    "redux": "^3.1.2"
  },
  "devDependencies": {
    "autoprefixer": "^6.3.6",
    "autoprefixer-loader": "^3.2.0",
    "babel-core": "^6.9.1",
    "babel-loader": "^6.2.0",
    "babel-preset-es2015": "^6.3.13",
    "babel-preset-react": "^6.5.0",
    "babel-preset-react-hmre": "^1.1.1",
    "babel-register": "^6.3.13",
    "css-loader": "^0.23.1",
    "extract-text-webpack-plugin": "^1.0.1",
    "node-sass": "^3.7.0",
    "sass-loader": "^3.2.0",
    "style-loader": "^0.13.1",
    "webpack": "^1.13.1",
    "webpack-dev-middleware": "^1.6.1",
    "webpack-hot-middleware": "^2.10.0"
  }

1 个答案:

答案 0 :(得分:5)

对于类静态属性,您需要在Babel中安装并启用stage-0 preset

$ npm install --save-dev babel-preset-stage-0

确保您的Babel配置使用它:

"presets": [ "es2015", "stage-0" ]