简体   繁体   English

Babel在箭头函数上引发语法错误

[英]Babel throws a syntax error on arrow function

I'm trying to adapt this code for a small project with React, but I'm having trouble, and I don't know how to fix this, because I don't know if this is the original code or my Babel that's buggy (like, missing a library or something), or if I can't because React. 我正在尝试使用React将这个代码改编成一个小型项目,但遇到了麻烦,而且我不知道如何解决这个问题,因为我不知道这是原始代码还是我的Babel有问题(例如,缺少库之类的东西),或者如果我不能,因为React。

So the thing is I had to adapt some functions because otherwise Babel would throw an unexpected token on them, ie, 所以事情是我必须适应一些功能,因为否则Babel会在它们身上抛出意外的标记,即

static propTypes = { // unexpected '='
  onRequestSort: PropTypes.func.isRequired,
  onSelectAllClick: PropTypes.func.isRequired,
  order: PropTypes.string.isRequired,
  orderBy: PropTypes.string.isRequired,
};

became 成为

static get propTypes() {
    return {
        onRequestSort: PropTypes.func.isRequired,
        onSelectAllClick: PropTypes.func.isRequired,
        order: PropTypes.string.isRequired,
        orderBy: PropTypes.string.isRequired,
    }
}

and this: 和这个:

handleRequestSort = (event, property) => { ... } // unexpected '='

became this: 变成这样的:

handleRequestSort(event, property) { ... }

For my main issue, I replaced this: 对于我的主要问题,我替换为:

createSortHandler = property => event => { // unexpected '='
    this.props.onRequestSort(event, property);
};

by this 这样

createSortHandler(property) {
    return function (event) {
        this.props.onRequestSort(event, property);
    };
};

However, if I click on the arrow on the table that triggers the order's change, I get cannot read props of undefined . 但是,如果单击触发订单更改的表格上的箭头,我将cannot read props of undefined Otherwise, I get `unexpected token '=', as written in my code. 否则,将得到我的代码中所写的'意外令牌'='。

So my question is the following: is the original code buggy, is it my babel or is it something else? 所以我的问题是:原始代码是越野车,是我的通天塔还是其他东西? I'm currently on a Rails base with webpacker, but i don't believe this is the reason why I have these issues. 我目前在使用webpacker的Rails基础上,但是我不认为这是我遇到这些问题的原因。

You're missing the babel-plugin-transform-class-properties plugin to transform the class properties which is experimental syntax (hence the unexpected token = ). 您缺少babel-plugin-transform-class-properties插件来转换作为实验语法的类属性(因此,意外的token = )。 Include that in Babel configuration if you would like to use class properties for propTypes and class property arrow functions. 如果要对propTypes使用类属性和类属性箭头功能,请将其包括在Babel配置中。 The second error, that this.props is undefined is because you're using a regular function which this doesn't refer to the component. 第二个错误,那this.props未定义是因为你使用的常规功能, this并不是指该组件。 Return an arrow function instead: 而是返回一个箭头函数:

createSortHandler(property) {
  return (event) => {
    this.props.onRequestSort(event, property);
  };
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM