How can I bind this
to the React component when dealing with a nested function?
Here is a skeleton example. The reason that function2
is nested is so that you can get access to the variables defined in function1
class View extends Component{
constructor(props){
this.function1 = this.function1.bind(this);
this.state = {
a = null;
}
}
componentDidMount(){
function1();
}
function1(){
console.log(this); //will show the component correctly
var param1 = 10;
//call a second function that's defined inside the first function
function2();
function function2(){
console.log(this); //undefined
var a = param1*2;
this.setState({ a : a}); //won't work because this is undefined
}
}
render(){
return(
<div>
<p> Hello </p>
</div>
)
}
}
Why not just use arrow functions? That would make sure this
is referenced properly. I am assuming you can use ES6
.
function1 = () => {
console.log(this);
var param1 = 10;
const function2 = () => {
console.log(this);
var a = param1*2;
this.setState({ a });
}
function2(); // inkove the function
}
OR if you only want to use ES5
, then this could also work
function1() {
console.log(this);
var param1 = 10;
function function2() {
console.log(this);
var a = param1*2;
this.setState({ a });
}
function2.bind(this)() // to invoke the function
}
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