import React, {Component} from 'react';
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = {
number: 0
}
this.cntIncrease = this.cntIncrease.bind(this);
this.cntDecrease = this.cntDecrease.bind(this);
}
cntIncrease() {
this.setState({
number: this.state.number + 1
})
}
cntDecrease() {
this.setState({
number: this.state.number - 1
})
}
render() {
return (
<>
<h1>{this.state.number}</h1>
<button onClick={this.cntIncrease}>+ 버튼</button>
<button onClick={this.cntDecrease}>- 버튼</button>
</>
)
}
}
export default Counter;
=========================================
import React, {Component} from 'react';
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = {
number: 0
}
}
cntIncrease() {
this.setState(
{
number: this.state.number + 1
},
() => {
alert('counter: ' + this.state.number);
}
)
}
render() {
const {number} = this.state;
return (
<>
<h1>{number}</h1>
<button onClick={() => this.cntIncrease()}>
+ 버튼
</button>
</>
)
}
}
export default Counter;