【问题标题】:How to solve the problem Support for the experimental syntax 'classProperties' isn't currently enabled如何解决问题当前未启用对实验语法“classProperties”的支持
【发布时间】:2021-02-21 18:44:20
【问题描述】:

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

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

这是关于我的工作的代码 sn-p...

 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”的支持

有人可以帮帮我吗?

【问题讨论】:

    标签: javascript reactjs babeljs


    【解决方案1】:

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

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

    【讨论】:

    • 这不是回答关于classProperties的问题
    猜你喜欢
    • 2019-02-13
    • 2020-03-06
    • 2022-10-22
    • 2021-04-26
    • 2020-08-07
    • 2019-11-10
    • 2019-12-12
    • 1970-01-01
    • 2020-02-09
    相关资源
    最近更新 更多