【问题标题】:Missing class properties transform缺少类属性转换
【发布时间】:2016-12-24 09:16:09
【问题描述】:

所以我刚刚尝试获取 google 材料对话框。 我对流星很陌生,所以对你来说答案可能比对我更明显。

即便如此,我的控制台还是给了我这个错误:

Missing class properties
   transform.

在这个文件的第 16 行:

export default class DialogExampleCustomWidth extends React.Component {

  state = {
    open: false,
  };

  handleOpen = () => {
    this.setState({open: true});
  };

  handleClose = () => {
    this.setState({open: false});
  };

  render() {
    const actions = [
      <FlatButton
        label="Cancel"
        primary={true}
        onTouchTap={this.handleClose}
      />,
      <FlatButton
        label="Submit"
        primary={true}
        onTouchTap={this.handleClose}
      />,
    ];

    return (
      <div>
        <RaisedButton label="Dialog With Custom Width" onTouchTap={this.handleOpen} />
        <Dialog
          title="Dialog With Custom Width"
          actions={actions}
          modal={true}
          contentStyle={customContentStyle}
          open={this.state.open}
        >
          This dialog spans the entire width of the screen.
        </Dialog>
      </div>
    );
  }
}

错误出现在state = { 我已经阅读了多篇文章,但似乎无法理解。感谢您的帮助和时间

【问题讨论】:

  • 实例属性在 JS 中没有标准化。您需要在构造函数中初始化您的状态。 constructor() { this.state = ... }
  • 它说在超级 @zerkms 之前不允许使用 'this'
  • 所以 - 打电话给super()?
  • 对于其他发现此问题并使用 SublimeText 的人。由于@henk 的回答解决了这个问题,然后我跟着Dan Abramov's blog post 修复了SublimeText 中的ESLint / Babel linting - 否则只会在state = { 行抛出一个错误并且没有进一步。

标签: reactjs meteor


【解决方案1】:

Meteor 默认不支持箭头功能,但今天你可以简单地改变它:

add the following package:

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

在您的项目中编辑您的 package.json 并在其中添加以下内容以制作 the package work:

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

  }

【讨论】:

  • 这个答案效果很好。吹毛求疵,但通过流星支持箭头功能,只是类属性不支持。
【解决方案2】:

像这样更改您的代码:

export default class DialogExampleCustomWidth extends React.Component {

  consructor(props){
    super(props);
    this.state = {
      open: false,
  };

  handleOpen = () => {
    this.setState({open: true});
  };

  ......
}

【讨论】:

    【解决方案3】:

    如果要设置初始状态值,应该在构造函数中设置。

    一个例子是这样的:

    constructor(props) {
        super(props)
        this.state = {
            open: false
        }
    }
    

    这里要指出的两件事:

    1. 如果您使用构造函数,则始终需要使用 super() 调用基类
    2. 如果您希望能够在构造函数中访问 this.props,请将 props 传递给基类。在这种情况下 super() 可以,因为您没有访问 this.props。

    阅读更多 herehere(直接来自 React 团队)

    【讨论】:

      猜你喜欢
      • 2017-03-19
      • 1970-01-01
      • 2018-11-16
      • 2016-06-01
      • 1970-01-01
      • 2023-01-19
      • 2019-02-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多