react设置static defaultProps报错问题解决

今天做个简单的demo,老是报static defaultProps语法错误,代码如下


import React,{Component} from 'react';
import ReactDOM from 'react-dom';

class Button extends  Component{
    constructor(props) {
        super(props);

    }
    static defaultProps = {
        color:'blue',
        text:'Confirm',
    }

    render(){
        const{ color,text} = this.props;
        return (
            <button className={`btn btn-${color}`}>
                <em>{text}</em>
            </button>
        )
    }
}
ReactDOM.render(
    <Button color="red" text="Danger!"  />,
    document.getElementById('app')
);

报错如图
这里写图片描述

Module build failed: SyntaxError: F:/reactdemo/reactapp/main.js: Unexpected token (10:24)

   8 |
   9 |     }
> 10 |     static defaultProps = {
     |                         ^
  11 |         color:'blue',
  12 |         text:'Confirm',
  13 |     }

最后查查资料,发现如果babel设置为es6的转码方式,会报错,因为定义静态属性不属于es6,而在es7的草案中。ES6的class中只有静态方法,没有静态属性。
由于是用ES6 class语法创建组件,其内部只允许定义方法,而不能定义属性,class的属性只能定义在class之外。所以defaultProps要写在组件外部。

解决方案
将babel设置为es7的转码方式,在项目下安装babel-preset-stage-0

npm install babel-preset-stage-0 --save-dev

在项目根目录配置.babelrc文件

{
  "presets": ["es2015", "stage-0"]
}

webpack.config.js配置文件修改

module: {
        rules: [ {
            test: /\.jsx?$/,
            exclude: /node_modules/,
            loader: 'babel-loader',
            query: {
                presets: ['es2015', 'react','stage-0']
            }
        }]
    }

加入stage-0后就能尝试es7语法了,static也能在class内部定义属性了!

猜你喜欢

转载自blog.csdn.net/yilanyoumeng3/article/details/79627646