我正在尝试适应 this code对于 React 的一个小项目,但我遇到了麻烦,我不知道如何解决这个问题,因为我不知道这是原始代码还是我的 Babel 有问题(比如,缺少库或其他东西) ),或者如果我不能因为 React。
所以问题是我必须调整一些函数,否则 Babel 会在它们上面抛出一个意想不到的标记,即
static propTypes = { // unexpected '='
onRequestSort: PropTypes.func.isRequired,
onSelectAllClick: PropTypes.func.isRequired,
order: PropTypes.string.isRequired,
orderBy: PropTypes.string.isRequired,
};
成为
static get propTypes() {
return {
onRequestSort: PropTypes.func.isRequired,
onSelectAllClick: PropTypes.func.isRequired,
order: PropTypes.string.isRequired,
orderBy: PropTypes.string.isRequired,
}
}
还有这个:
handleRequestSort = (event, property) => { ... } // unexpected '='
变成了这个:
handleRequestSort(event, property) { ... }
对于我的主要问题,我替换了这个:
createSortHandler = property => event => { // unexpected '='
this.props.onRequestSort(event, property);
};
由此
createSortHandler(property) {
return function (event) {
this.props.onRequestSort(event, property);
};
};
但是,如果我单击触发订单更改的表上的箭头,我将得到 cannot read props of undefined
。否则,我会得到“意外的标记‘=’,如我的代码中所写。
所以我的问题如下:原始代码有问题吗,是我的 babel 还是其他东西?我目前在使用 webpacker 的 Rails 基础上,但我不认为这是我遇到这些问题的原因。
最佳答案
你错过了 babel-plugin-transform-class-properties
用于转换实验性语法的类属性的插件(因此出现意外标记 =
)。如果您想为 propTypes
和类属性箭头函数使用类属性,请将其包含在 Babel 配置中。第二个错误,即 this.props
未定义,是因为您使用的是 this
未引用组件的常规函数。而是返回一个箭头函数:
createSortHandler(property) {
return (event) => {
this.props.onRequestSort(event, property);
};
};
关于javascript - Babel 在箭头函数上抛出语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44997304/