reactjs - React 组件中出现意外标记 '='

标签 reactjs babeljs

我可能缺少装载机吗?我认为我们应该能够在组件体中使用这些 ES6 函数,以避免必须执行 .bind(this)语法react docs

    ERROR in ./client/admin-side/components/Form.jsx
Module build failed: SyntaxError: Unexpected token (15:17)

  14 | 
> 15 |     handleChange = (event) => {
     |                  ^
  16 |         this.setState({value: event.target.value})
  17 |     }

我的 .babelrc 有以下内容:

{
    "presets": ["env", "react"],
    "plugins": ["transform-object-rest-spread"]
}

我正在使用babel-loader对于 js/jsx 文档

最佳答案

您需要使用transform-class-properties插件来使用类字段,您可以像安装它

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

并将其用作插件

{
    "presets": ["env", "react"],
    "plugins": ["transform-object-rest-spread", "transform-class-properties"]
}   

transform-object-rest-spread 用于其余扩展语法,类似于

const {a, b, ...rest} = this.props

根据documentation :

This presents two related proposals: "class instance fields" and "class static fields".

"Class instance fields" describe properties intended to exist on instances of a class (and may optionally include initializer expressions for said properties).

"Class static fields" are declarative properties that exist on the class object itself (and may optionally include initializer expressions for said properties).

This proposal is currently at Stage 2.

您还可以通过安装使用预设 stage-2 来解决此问题

npm install --save-dev babel-preset-stage-2

并像这样使用它

{
    "presets": ["env", "react", "stage-2"],
    "plugins": ["transform-object-rest-spread"]
} 

关于reactjs - React 组件中出现意外标记 '=',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48801984/

相关文章:

javascript - 为什么 useState 函数不每次都初始化状态?

javascript - 使用 React 从 HTML 文件调用 .js 文件中的 Javascript 函数

reactjs - 如何在 Next.js 静态站点生成上获取 URL 查询字符串?

babeljs - React 服务器端渲染意外 token 、JSX 和 Babel

node.js - Node 错误 : SyntaxError: Unexpected token import

javascript - 巴别塔 6 : Too many arguments passed error

javascript - 错误: Couldn't find preset "react-hmre" relative to directory

javascript - 链接到 Scroll,TypeError : this. props.parentMethod 不是函数

javascript - React : NextJS, 我需要 2 台服务器进行部署吗?

javascript - ReactJS - 在不提供 HTTP 文件的情况下无法运行 babel 代码