不能使用胖箭头功能(ES6)进行反应 [英] Can't use fat arrow functions (ES6) in react
问题描述
我在使用胖箭头功能时遇到了一些问题。如果函数不是匿名的,它会抱怨语法并且不会编译。
I've had some issues using fat arrow functions in react. If the function is not anonymous, it complains about the syntax and won't compile.
这个:
handleItemClick = (e, { name }) => this.setState({ activeItem: name });
给我:
BabelLoaderError: SyntaxError: Unexpected token (20:20)
它指向等号(handleItemClick'=')。
It points to the equal sign(handleItemClick'=').
然而这很好用:
onClick={ (arg) => {//Do something} };
我的webpack配置有什么问题,或者其他我错过的东西?感谢任何提示。
Is there something wrong with my webpack config, or something else i'm missing? Thankful for any hints.
module.exports = {
entry: PATHS.app_path,
output:{
path: PATHS.build,
filename: 'index.js'
},
devServer:{
inline: true,
port: 3333,
contentBase: PATHS.build,
publicBase: PATHS.build,
historyApiFallback: true
},
resolve: {
root: path.resolve('./public'),
extensions: ['', '.js', '.jsx']
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel',
query: {
presets: ['es2015', 'react']
}
},
{
test: /\.css$/,
loader: 'style-loader'
},
{
test: /\.css$/,
loader: 'css-loader',
query: {
modules: true,
localIdentName: '[local]'
//localIdentName: '[name]__[local]___[hash:base64:5]'
}
},
{ test: /\.(png|woff|woff2|eot|ttf|jpg)$/, loader: 'url-loader?limit=100000' },
{
test: /.*\.svg$/,
loaders: [
'file-loader',
'svgo-loader?' + svgoConfig,
]
}
]
}
};
推荐答案
您正在尝试使用类字段,它们不是ES6的一部分,并且不在es2015中,并且会对预设做出反应。
You are trying to use class fields, which are not part of ES6, and aren't covered by es2015, and react presets.
您可以使用类属性转换babel插件:
query: {
presets: ['es2015', 'react'],
plugins: ["transform-class-properties"]
}
或使用 babel stage-2预设,包含转换插件:
Or use the babel stage-2 preset, that includes the transform plugin:
query: {
presets: ['es2015', 'react', 'stage-2']
}
不要忘记 npm install
你选择的那个ose。
Don't forget to npm install
the one that you choose.
这篇关于不能使用胖箭头功能(ES6)进行反应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!