Public class fields allows us to add instance properties and methods to the class definition with assignment operator. This helps to simplify event callbacks and state initialisation with component
class App extends React.Component{
constructor(...args){
super(...args)
this.state = {clicks: 0}
}
handleClick() {
this.setState(prevState=> return {clicks:prevState.clicks +1})
}
render () {
return (
<div>
<div>
click Count: {this.state.clicks}
</div>
<button onClick={this.handleClick}> Click Me </button>
</div>
)
}
}
//There is a problem that the state is not a function
//Because we are passing handleClick to the onclick callback and the this on the function is not bound to anything
//
//solution 1
onClick={this.handleClick} becomes onClick={() =>this.handleClick}
//it drawback is when we have to pass args to the arrow function and the handleClick must receive the arts too. so imagine too
//many args,
onClick={this.handleClick} becomes onClick={(...args) =>this.handleClick(...args)}
//solution 2
onClick={this.handleClick} becomes onClick={this.handleClick.bind(this)}
//solution 3
//in the constructor
this.handleclick = his.handleClick.bind(this)
//in the callback
onClick={this.handleClick}
//solution 4
//Public class fields
handleClick= function() {
this.setState(prevState=> return {clicks:prevState.clicks +1})
}
//in the callback
onClick={this.handleClick}
//solution 5
//Public class fields
handleClick= () => {
this.setState(prevState=> return {clicks:prevState.clicks +1})
}
//in the callback
onClick={this.handleClick}
//solution 5
//this gets rid of the constructor
//state
state = {clicks: 0}
//Public class fields
handleClick= () => {
this.setState(prevState=> return {clicks:prevState.clicks +1})
}
//in the callback
onClick={this.handleClick}