一个 react 组件,将显示计数器的当前值。
计数器应从 0 开始。 应该有一个加1的按钮。 还应该有一个减 1 的按钮。
我无法理解这个问题,我错过了什么或者语法错误。
const React = require('react');
class Counter extends React.Component{
constructor(...args){
super(...args);
this.state = { counter: 0 };
}
// Your event handlers
cincrement = () => {
this.setState({ counter: this.state.counter+1 });
};
cdecrement = () => {
this.setState({ counter: this.state.counter-1 });
};
render() {
return (
<div>
<h1>{this.state.counter}</h1>
<button type="button" onClick={this.cincrement}>
Decrement
</button>
<button type="button" onClick={this.cdecrement}>
Increment
</button>
</div>
)
}
}
运行代码时遇到的错误
/runner/node_modules/babel-core/lib/transformation/file/index.js:590 throw err; ^
SyntaxError: /home/codewarrior/index.js: Unexpected token (16:13) 14 | // Your event handlers 15 |
block 引用>16 | cincrement = () => { | ^ 17 | this.setState({ counter: this.state.counter+1 }); 18 | }; 19 |
at Parser.pp$5.raise (/runner/node_modules/babylon/lib/index.js:4454:13) at Parser.pp.unexpected (/runner/node_modules/babylon/lib/index.js:1761:8) at Parser.pp$1.parseClassProperty (/runner/node_modules/babylon/lib/index.js:2571:50) at Parser.parseClassProperty (/runner/node_modules/babylon/lib/index.js:6157:20) at Parser.pp$1.parseClassBody (/runner/node_modules/babylon/lib/index.js:2516:34) at Parser.pp$1.parseClass (/runner/node_modules/babylon/lib/index.js:2406:8) at Parser.pp$1.parseStatement (/runner/node_modules/babylon/lib/index.js:1843:19) at Parser.parseStatement (/runner/node_modules/babylon/lib/index.js:5910:22) at Parser.pp$1.parseBlockBody (/runner/node_modules/babylon/lib/index.js:2268:21) at Parser.pp$1.parseBlock (/runner/node_modules/babylon/lib/index.js:2247:8)
最佳答案
你的 babel 配置似乎不包括 class properties syntax
您可以使用普通的原型(prototype)方法,然后在构造函数中预先绑定(bind)它们
此外,由于您的下一个状态取决于上一个状态,您应该将回调传递给 setState
const React = require('react');
class Counter extends React.Component{
constructor(...args){
super(...args);
this.state = { counter: 0 };
this.cincrement = this.cincrement.bind(this);
this.cdecrement= this.cdecrement.bind(this)
}
// Your event handlers
cincrement(){
this.setState(state => ({ counter: state.counter+1 }));
}
cdecrement() {
this.setState(state => ({ counter: state.counter-1 }));
}
render() {
return (
<div>
<h1>{this.state.counter}</h1>
<button type="button" onClick={this.cincrement}>
Decrement
</button>
<button type="button" onClick={this.cdecrement}>
Increment
</button>
</div>
)
}
}
关于javascript - 一个reactjs模块,用于增加按下按钮的计数 -,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54064414/