gpt4 book ai didi

javascript - React 组件 render 方法中的语法错误

转载 作者:行者123 更新时间:2023-11-30 20:18:44 25 4
gpt4 key购买 nike

React 组件中的render 方法如下所示:

render() {
return <h1>Hello, {this.props.name}</h1>;
}

错误是这样的:

Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: Unexpected token 20 | 21 | render() { > 22
| return <h1>Hello, {this.props.name}</h1>;
|

这是我的package.json:

{
"name": "test",
"version": "1.0.0",
"description": "",
"main": "webpack.config.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack",
"babel-version": "babel --version"
},
"babel": {
"presets": [
"env",
"react",
"stage-2"
]
},
"author": "",
"license": "ISC",
"devDependencies": {
"ajv": "^6.0.0",
"babel": "^6.23.0",
"babel-cli": "^6.26.0",
"babel-core": "^6.26.3",
"babel-loader": "^7.1.5",
"babel-plugin-transform-class-properties": "^6.24.1",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1",
"css-loader": "^1.0.0",
"less": "^3.8.0",
"less-loader": "^4.1.0",
"react": "^16.4.1",
"react-dom": "^16.4.1",
"reactstrap": "^6.3.1",
"style-loader": "^0.21.0",
"webpack": "^4.16.3",
"webpack-command": "^0.4.1"
},
"dependencies": {
"bootstrap": "^4.1.3",
"npm": "^6.3.0"
}
}

这是全类:

export default class SearchForm extends React.Component {
constructor(props) {
super(props);
this.state = {
name: ""
};
}

handleNameChange = (e) => {
this.setState({ name: e.target.value });
};

render() {
return <h1>Hello, {this.props.name}</h1>;
}
}

请注意,该类目前在功能方面没有意义,因为我一直在尝试找出语法错误。

我还有一个 .babelrc:

{
"plugins": [
["transform-class-properties"]
]
}

该方法非常简单,所以我看不出问题所在。感谢任何见解。

最佳答案

您最有可能收到错误,因为上面的类属性 (handleNameChange = (e) => { ... };) 是一个 stage 2 proposal .

如果你安装了 babel-preset-stage-2 并将它添加到你的 .babelrc 错误应该得到解决。

.babelrc

{
"presets": [
["env", "react", "stage-2"]
]
}

关于javascript - React 组件 render 方法中的语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51681314/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com