如何在 React 和 Webpack 中使用建议的 ECMAscript 类语法? [英] How to use the proposed ECMAscript class syntax with React and Webpack?

查看:19
本文介绍了如何在 React 和 Webpack 中使用建议的 ECMAscript 类语法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习建议的 ecmascript 类语法并将其与 React 一起使用,我已经成功地使用带有 webpack 的 babel 渲染了带有 es6 的组件.现在我想在构造函数之外声明的类中使用实例属性.例如:

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= ()=>{
   }
  }

在尝试执行此类操作时,我在property1"和func1"上收到错误意外令牌".另外,我在 webpack 中使用 babel 预设来响应 react 和 babel-preset-env 插件.

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.

我想限制在我的班级中使用this"关键字,所以我认为较新的 es7 班级可以实现这一点,我该怎么做?任何帮助将不胜感激.

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.

编辑 1:如答案中所建议的,我包含了babel-preset-stage-2"预设,并且我能够在类中包含构造函数之外的变量,但必须使用this"来引用它们.

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.

推荐答案

那个语法不是ES7"(我假设你的意思是 ES2016,也就是第 7 版).事实上,它甚至不是 ES2017.它仍然是一个 第 3 阶段提案.如果 ES2018 能够在截止之前及时完成几个实现使其达到第 4 阶段,它可能会成为 ES2018.

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.

要与 Babel 一起使用,请启用 stage-3 预设 或该功能的特定插件(transform-class-properties).

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

这篇关于如何在 React 和 Webpack 中使用建议的 ECMAscript 类语法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆