How to use the proposed ECMAscript class syntax with React and Webpack?

☆樱花仙子☆ 提交于 2019-12-25 08:56:58

问题


I am trying to learn the proposed class syntax for ecmascript and using it with React, i have successfully rendered components with es6 using babel with webpack. Now i want to use instance properties inside classes which are declared outside of the constructor. For eg:

class MyComponent extends React.Component{
  constructor(props){
   super(props)
  }

  property1= "new property"; 
  func1= ()=>{
   }
  }

I am getting the error "unexpected token" on 'property1' and 'func1' while trying to do something like this. also, i am using the babel presets for react and babel-preset-env plugins in webpack.

I want to limit the use of "this" keyword inside my class, so i thought the newer es7 classes could acheive that, how can i do this? any help would be appreciated.

Edit 1: as suggested in the answers, i included the "babel-preset-stage-2" preset , and i was able to include the variables outside of the constructor in the class, but have to use 'this' to reference them.


回答1:


That syntax isn't "ES7" (by which I assume you mean ES2016, aka the 7th edition). In fact, it's not even ES2017. It's still a Stage 3 proposal. It might make ES2018 if a couple of implementations get done in time for it reach Stage 4 before the cutoff.

To use it with Babel, enable the stage-3 preset or the specific plugin for that feature (transform-class-properties).




回答2:


You will need the correct babel plugin for this.

npm install --save-dev babel-plugin-transform-class-properties

.babelrc

{
  "plugins": ["transform-class-properties"]
}

More information: https://babeljs.io/docs/plugins/transform-class-properties/



来源:https://stackoverflow.com/questions/46511293/how-to-use-the-proposed-ecmascript-class-syntax-with-react-and-webpack

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!