Reputation: 4514
I am trying to call a function inside a class but confused with below syntax.
Why I need to use bind method when calling a function?
Why arrow function is not getting executed?
import React, { Component } from 'react'
import { Text, View } from 'react-native'
//arrow function not getting executed!
myFun = data => {
console.warn(data);
}
myFun(data){
console.warn(data);
}
class Hello extends Component {
render() {
return (
<View>
{this.myFun("first")}
{this.myFun.bind(this, "second")}
</View>
);
}
}
export default Hello;
Note: I have removed comment from the first method!
Upvotes: 0
Views: 4131
Reputation: 765
Functions should be called inside class to get them available with this context.
import React, { Component } from 'react'
import { Text, View } from 'react-native'
class Hello extends Component {
constructor(props) {
super(props);
}
//both normal fun and arrow fun should be inside class to get it executed!
myFun1 = data => {
console.warn(data);
}
myFun2(data){
console.warn(data);
}
render() {
return (
<View>
{this.myFun("first")}
{this.myFun2.bind(this, "second")}
</View>
);
}
}
export default Hello;
When you are using this.myfun2.bind(this ) then you are adding it to current context of **this **. Basically after then only you will be able to do this.state , this.props, this.setstate etc
Also bind function returns a bounded function that, when executed later, the function will have the correct context ("this") for calling the original function. So bind function can be used when the function needs to be called later in certain events when it's useful.
Upvotes: 1
Reputation: 24314
The keyword this
retains the value of the enclosing lexical context in our case the Hello class
. As you can see in your example this
which means Hello
doesn't have myFun
& yet you're trying to call that function!
So either you put the function inside the class or you change your call method to myFun("first")
shortly.
Lastly, if you need to use this
keyword inside your function, then you'll have to use the bind(this)
method.
Upvotes: 1
Reputation: 577
Put the function into the class
Bind the function in the constructor:
this.handleChange = this.handleChange.bind(this);
The bind method doesn't execute the function/method, only it return the function with new context (this)
Upvotes: 1
Reputation: 138
you need to call the function as below.
import React, { Component } from 'react'
import { Text, View } from 'react-native'
myFun = data => {
console.warn(data);
}
class Hello extends Component {
render() {
return (
<View>
{()=>this.myFun("first")}
</View>
);
}
}
export default Hello;
Upvotes: 0