我在ReactJS应用程序上获得了意外的令牌。但我相信语法是正确的。
import React, { Component } from 'react';
class Auth extends Component {
constructor(){
super()
this.state={
authStatus: "Sign In",
isAuthenticated: false
}
}
AuthMe = () =>{
console.log("Working")
}
render() {
return (
<button type="button" onClick={this.AuthMe}>{this.state.authStatus}</button>
);
}
}
export default Auth;
> ./src/components/Auth/index.js中的错误 模块构建失败:SyntaxError:意外的令牌(11:11)
> 11 | AuthMe = () =>{
| ^
12 | console.log("Working")
13 | }
我错过了什么?
这是我的webpack.config.js
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
publicPath: '/',
},
module: {
rules: [{
test: /\.jsx?$/,
exclude: [
path.resolve(__dirname, 'node_modules'),
],
loader: 'babel-loader',
}]
},
resolve: {
extensions: ['.json', '.js', '.jsx', '.css']
},
devtool: 'source-map',
devServer: {
historyApiFallback: true
}
};
.babelrc
{
"presets": ["es2015","react","stage-0"],
"plugins": ["transform-decorators-legacy"]
}
答案 0 :(得分:0)
尝试:
<input type="checkbox"
ng-checked="isDrinkInService(drink.Id)"
ng-click="addOrDeleteDrink(drink)" />
注意: class Auth extends Component {
constructor(){
super()
this.state={
authStatus: "Sign In",
isAuthenticated: false
}
}
AuthMe() {
console.log("Working")
}
render() {
return (
<button type="button" onClick={this.AuthMe}>{this.state.authStatus}</button>
);
}
}
不仅仅是常规功能而且不是胖箭功能,如果这对您很重要。
将胖箭头函数用作类函数不是标准的ES6语法(the proposal目前是阶段2),因此您需要additional babel plugin来添加该功能。
有关详细信息,请参阅this answer。
答案 1 :(得分:0)
我在此之前回答了这个问题:Arrow Function syntax not working with webpack?
TLDR那是胖箭头还没有出现在ES201的标准中。你需要添加一个额外的babel变换。
npm install --save-dev babel-plugin-transform-class-properties
{
"presets": ["es2015","react","stage-0"],
"plugins": ["transform-decorators-legacy", "transform-class-properties"]
}
答案 2 :(得分:-2)
使用var AuthMe或const AuthMe而不是AuthMe
import React, { Component } from 'react';
class Auth extends React.Component {
constructor(){
super()
this.state={
authStatus: "Sign In",
isAuthenticated: false
}
}
var AuthMe = () =>{
console.log("Working")
}
render() {
return (
<button type="button" onClick={this.AuthMe}>{this.state.authStatus}</button>
);
}
}
export default Auth;