I have written a simple react code that just increases the value of 'numbers' when clicking on the button. It works well.
import React from "react";
import "./styles.css";
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
numbers: 1
};
}
handleClick = () =>{
this.setState({
numbers: this.state.numbers+1
})
}
render() {
return (
<div className="App">
<h1>Incrementer</h1>
<input type="submit" name="submit" value="increment" onClick={this.handleClick}/>
<br/>
<h1>{this.state.numbers}</h1>
</div>
);
}
}
I have a query regarding the line:
<input type="submit" name="submit" value="increment" onClick={this.handleClick}/>
When I change the above line as shown below, it still works:
<input type="submit" name="submit" value="increment" onClick={() => this.handleClick()}/>
But, if I change it to
onClick={this.handleClick()}
or
onClick={handleClick()}
or
onClick={function clickFunction(){this.handleClick()}}
it does not compile.
onClick={() => this.handleClick()}
I'm not able to understand the difference. Kindly help.