React Component渲染方法

时间:2018-08-03 23:56:15

标签: javascript reactjs ecmascript-6

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"]
  ]
}

该方法非常简单,因此我看不出问题出在哪里。感谢您提供任何见识。

1 个答案:

答案 0 :(得分:1)

您很可能会收到错误消息,因为(handleNameChange = (e) => { ... };)上的class属性是stage 2 proposal

如果您安装babel-preset-stage-2并将其添加到.babelrc,则该错误应得到解决。

.babelrc

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