I am trying to change the state on the click of a button I created through DOM methods. I tried passing "this" as a variable through the arguments of the function
var self="this"
b.addEventListener("click", function(self){
self.setState({health:100}) })
and also tried adding .bind(this) at the end of the function but no luck.
b.addEventListener("click", function(){
this.setState({health:100}) })
This issue can be handled using right declaration and definition of self
.
OR with the help of arrow function(implicit Lexical scope)
componentDidMount(){
//assuing b defined
//1. if you want to use self
const self = this; // this should not be double quoted;
b.addEventListener("click", function () {
self.setState({ health: 100 });
}
// 2. using arrow function ( implicit lexical scope)
b.addEventListener("click", ()=> {
this.setState({ health: 100 });
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With