The Test component has a state of num
, the component implements the function of clicking the button num+1, the button is bound to the self-increment method, the keyup
is also bound to the method, the method uses the setState
to re-render the value of num
, but the effect of clicking the button with the mouse is not the same as the keyboard trigger event. Could you tell me why, please?
When I click the button, console logs the num
first, then done
.
But when I press enter, console logs done
, then the num
.
React15.5
class Test extends React.PureComponent {
constructor(){
super();
this.state = {
num : 1
}
}
add = () => {
const {num} = this.state;
this.setState({num:num+1},()=>{
console.log("done")
})
console.log(this.state.num)
}
componentDidMount() {
document.body.addEventListener('keyup', this.add);
}
componentWillUnmount() {
document.body.removeEventListener('keyup', this.add);
}
render() {
return(
<Button onClick={this.add} >add</Button>
<span>{this.state.num}</span>
)
}
}