首页 > 解决方案 > 如何解决问题当前未启用对实验语法“classProperties”的支持

问题描述

我有这个错误当我尝试运行应用程序时,当前未启用对实验语法“classProperties”的支持。react js

<span>当我单击 ` 时,我试图增加 a 中的值

这是关于我的工作的代码片段......

 import React, {Component} from 'react';

 export default class Test extends Component {

  constructor(props) {
    super(props);

    this.state = {
      counter: 0
    }
  }

  handleClick = () =>{ //this is where it triggers the error mentioned above
    this.setState((state) => ({counter: state.counter+1}));
  }


  render() {
    return (
      <div>
        <span>{this.state.counter}</span>
        <input type="button" value={this.props.value}
               onClick={this.handleClick} />
      </div>
    );
  }

}

但我收到此错误当前未启用对实验语法“classProperties”的支持

有人可以帮帮我吗?

标签: javascriptreactjsbabeljs

解决方案


您必须小心 JSX 回调中 this 的含义。在 JavaScript 中,默认情况下不绑定类方法。如果忘记绑定 this.handleClick 并将其传递给 onClick,则在实际调用该函数时 this 将是未定义的,因此您需要在构造函数中编写以下代码

  constructor(props) {
    super(props);

    this.state = {
      counter: 0
    }
    this.handleClick = this.handleClick.bind(this);
  }

推荐阅读