I keep seeing answers that say to use => or .bind(this) but neither of those solutions worked.
import React, { Component } from \'react\';
import { View, Tex
you need to bind your action otherwise you can see error called undefined in your browser there are three methods for binding your action
for eg-
export class EventBind extends Component{
constructor(){
super()
this.state = {
msg:'hello'
}
}
chngHandler(){
this.setState({
msg:'Good bye'
})
}
render(){
return(
<div>
{this.state}
<button onClick={this.chngHandler.bind(this)}>click</button>
</div>
)
} }
()=>this.EventHandler()
for example-
export class EventBind extends Component{
constructor(){
super()
this.state = {
msg:'hello'
}
}
chngHandler(){
this.setState({
msg:'Good bye'
})
}
render(){
return(
<div>
{this.state}
<button onClick={()=>this.chngHandler()}>click</button>
</div>
)
}}`
3.Binding the event handler in the constructor
this.EventHandler = this.EventHandler.bind(this)
for example-:
export class EventBind extends Component{
constructor(){
super()
this.state = {
msg:'hello'
}
this.chngHandler = this.chngHandler.bind(this)
}
chngHandler(){
this.setState({
msg:'Good bye'
})
}
render(){
return(
<div>
{this.state}
<button onClick={this.chngHandler}>click me </button>
</div>
)
}}
because the binding happens once in the constructor this is better than a binding in the render method
3rd approach can also be done like this -:
export class EventBind extends Component{
constructor(){
super()
this.state = {
msg:'hello'
}
this.chngHandler = this.chngHandler.bind(this)
}
// chngHandler(){
// this.setState({
// msg:'Good bye'
// })
// }
chngHandler = ()=>{
this.setState({
msg:'Good Bye'
})
}
render(){
return(
<div>
{this.state}
<button onClick={this.chngHandler}>click me </button>
</div>
)
}}
works for react-native too when you use fat arrow functions inside the methods you are invoking another function.
eg
.then((response) => {
this.setState({....})
}