javascript - 如何解决问题当前未启用对实验语法“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”的支持
有人可以帮帮我吗?
解决方案
您必须小心 JSX 回调中 this 的含义。在 JavaScript 中,默认情况下不绑定类方法。如果忘记绑定 this.handleClick 并将其传递给 onClick,则在实际调用该函数时 this 将是未定义的,因此您需要在构造函数中编写以下代码
constructor(props) {
super(props);
this.state = {
counter: 0
}
this.handleClick = this.handleClick.bind(this);
}
推荐阅读
- javascript - 反应和引导 v4 延迟崩溃以渲染组件
- html - Bootstrap:当向下滚动页面时,jumbotron 图像被滚动:想要修复它
- scala - 在scala中添加两个由链表表示的数字
- sql-server - Spring boot:数据库连接未正确关闭
- three.js - Three.js:确定鼠标位置的世界坐标
- opencl - 隔离 CPU 内核上的 OpenCL
- angular - Angular 4更改路线
- c# - 带有 .NET Core 的 Material Design Lite 中的 Asp-for 标签助手
- ionic-framework - 相机的 FILE_URI 路径不适用于 IONIC 4
- ios - 实时事件数超过实时事件计数每日限制。事件不再是实时的