I'm a beginner in ReactJS and JavaScript, and I'm trying to make a test class in ReactJS that every time the user clicks on the button, counts the click and display it on the tag of the buttton, If I use a normal function like this, it doesn't work:
class Button extends React.Component
{
state = { counter : 0}
test = function ()
{
this.setState({
counter : this.state.counter + 1
})
}
render(){
return(<button onClick={this.test}>{this.state.counter}</button>)
};
}
But when I use Arrow Function on test , it works perfect :
class Button extends React.Component
{
state = { counter : 0}
test = () => { ///////ONLY CHANGED THIS LINE
this.setState({
counter : this.state.counter + 1
})
}
render(){
return(<button onClick={this.test}>{this.state.counter}</button>)
};
}
Could anyone please explain me this behaviour ?