【发布时间】:2020-06-03 21:12:36
【问题描述】:
我需要将函数调用从组件移到单独的函数中
<MyComponent
getLabel={ ({buttonLabel, value }) => {
console.log('Placeholder');
console.log(buttonLabel);
console.log(value ? value.map( c => { return c.label}) : []);
return 'test;
}} />
我试着像这样分开它:
class Results extends Component {
constructor(props) {
super(props);
this.state = {
}
this.getLabel = this.getLabel.bind(this);
getLabel = (buttonLabel, value) => {
console.log('Placeholder');
console.log(buttonLabel);
}
}
//this throws a compile error
/*getLabel = (buttonLabel, value) => {
console.log('Placeholder');
console.log(buttonLabel);
}*/
render() {
return (
<React.Fragment>
<MyComponent
getLabel={this.getLabel} />
</React.Fragment>
);
}
}
上面的例子抛出错误:
未捕获的类型错误:无法读取未定义的属性“绑定”
关于在浏览器中呈现。
如果我将函数移到构造函数之外,它会引发编译错误:
模块构建失败(来自 ./node_modules/babel-loader/lib/index.js):
目前不支持实验性语法“classProperties” 启用
那里有什么问题?
这是我的.babelrc:
{
"presets": [
"@babel/preset-env",
"@babel/preset-react"
],
"plugins": [
[
"@babel/plugin-proposal-class-properties"
]
]
}
编辑
我不知道为什么它之前不能正常工作,可能是 webpack 错误左右,不确定。
我在下面提供了对我有用的解决方案,这与我最初的意图非常接近。
【问题讨论】:
-
为什么要在构造函数中使用getLabel?
-
当您收到错误时,您是在构造函数中还是在外部使用 getLabel 运行此代码?
标签: reactjs babeljs babel-loader