此 ReactJS 代码有效并产生所需的输出:
import React from 'react'
class MyComponent extends React.Component {
state = {'x': 1}
render() {
console.log('render: this.state:', this.state)
return <div>{this.state.x}</div>
}
}
export default MyComponent
但是这个非常相似的 ES6 代码在使用 Node.js 运行时会导致错误:
class MyComponent {
state = {'x': 1}
render() {
console.log('render: this.state:', this.state)
return <div>{this.state.x}</div>
}
}
let c = new MyComponent()
c.render()
这是错误:
$ node foo.js
/Users/lone/foo.js:2
state = {'x': 1}
^
SyntaxError: Unexpected token =
当第一个示例在 ReactJS 中运行良好时,为什么第二个示例会导致错误?
最佳答案
该语法还不是 javascript 的标准部分(目前是 stage 3 proposal )。它可以在 babel's class-properties plugin 的帮助下使用将其转译为标准 JavaScript。您的 React 项目很可能包含此插件,这就是它在 React 中为您工作的原因。例如,Create-react-app 包含该插件。如果没有该插件,react 也无法使用该语法。
关于javascript - 类作用域中的变量赋值在 React 中有效,但在 ES6 中无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56027405/