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内部定义属性了!

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
当你尝试引入react-screenshot时,可能会遇到各种错误。以下是常见的一些错误以及可能的解决方法: 1. "Module not found: Can't resolve 'dom-to-image'" 这个错误通常是因为你还没有安装dom-to-image库,所以react-screenshot无法找到它。你可以通过运行以下命令来安装它: ``` npm install dom-to-image ``` 2. "TypeError: Cannot read property 'toBlob' of undefined" 这个错误通常是因为你的浏览器不支持canvas.toBlob()方法。你可以尝试使用polyfill解决这个问题。你可以在你的项目中安装canvas-toBlob.js: ``` npm install canvas-toblob ``` 然后在你的代码中引入它: ``` import 'canvas-toblob'; ``` 3. "TypeError: Cannot read property 'getCanvas' of undefined" 这个错误通常是因为你没有正确地使用react-screenshot组件。你需要确保你在组件上正确地绑定ref,并且在调用getCanvas()方法之前,确保你已经调用了capture()方法。以下是一个正确的示例: ``` import React, { useRef } from 'react'; import Screenshot from 'react-screenshot'; function App() { const screenshotRef = useRef(null); const handleCapture = () => { screenshotRef.current.capture(); const canvas = screenshotRef.current.getCanvas(); // do something with canvas }; return ( <div> <button onClick={handleCapture}>Capture</button> <Screenshot ref={screenshotRef}> <div>Content to capture</div> </Screenshot> </div> ); } ``` 希望这些解决方法能够帮助你解决react-screenshot的引入问题
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

前端岚枫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值