反应JSX defaultProps语法错误

时间:2018-08-13 08:36:12

标签: reactjs syntax-error jsx

我尝试使用以下代码:

import React, { Component } from 'react';

export default class Hello extends Component {
    static defaultProps = {
        somename: "World!"
    }
    render() {
        return (
            <h1>Hello {this.props.somename}</h1>
        );
    }
}

但是我然后尝试在webpack中构建它,但在这里出现语法错误:

静态defaultProps = {

我以前没有使用过jsx和后来的ECMAScript标准。有人可以解释一下该怎么写吗?

UPD: 我的webpack配置:

const webpack = require('webpack');
const path = require('path');
const entryPath = path.resolve(__dirname, 'src/client/js');

module.exports = {
  mode: 'development',
  entry: {
    app: entryPath + '/app.js',
    main: entryPath + '/main.js',
  },
  output: {
    path: path.resolve(__dirname, 'public/js'),
    filename: '[name].js',
  },
  module: {
        rules: [
            {
                test: /\.jsx?$/, 
                exclude: /(node_modules)/,  
                loader: "babel-loader", 
                options: {
                    presets: ["env", "react"] 
                }
            }
        ]
    }
};

2 个答案:

答案 0 :(得分:1)

如果您不想玩.babelrc文件,可以这样重写代码:

import React, { Component } from 'react';

class Hello extends Component {
    render() {
        return (
            <h1>Hello {this.props.somename}</h1>
        );
    }
}

Hello.defaultProps = {
    somename: "World!"
}

export default Hello

如果这不是一个选项,并且您希望使用静态类属性,那么您将要使用Babel插件。我使用babel-plugin-transform-class-properties。有一个great tutorial on the Babel website that shows you how to implement this.

在本教程中,安装是通过以下方式完成的:

npm install --save-dev babel-plugin-transform-class-properties

然后将以下代码添加到您的.babelrc

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

答案 1 :(得分:0)

代替创建静态函数,请执行以下操作:

import React, { Component } from 'react';

class Hello extends Component {
    render() {
        return (
            <h1>Hello {this.props.somename}</h1>
        );
    }
}

Hello.defaultProps = {
    somename: 'World!',
}

export default Hello;