-2

i try to pass onChangeText() to a child component in react native,its worked :

onChangText(value){
    console.log(value)
}

render() {

    return (

        <View style={{flex:1}}>
            <Ui  
                onChangeText={this.onChangText()}  
            />
        </View>
    )
}

but when i call other function's(in parent) like below:

loger(value){
    console.log(value)
}
onChangText(value){
    this.loger(value)
}

render() {

    return (

        <View style={{flex:1}}>
            <Ui  
                onChangeText={this.onChangText()}
            />
        </View>  
    )
} 

i got error: this.loger is not a function

enter image description here

amirhosein
  • 844
  • 9
  • 24

2 Answers2

1

Two things you need to take care of

First, while passing the function to child, you need not invoke it and just pass the reference like

 <Ui  
      onChangeText={this.onChangText}
 />

Second, whenever you need to use this keyword inside the called function, you should bind the function to the correct context. In your case, you need to bind it to the context of the parent class and hence you can use arrow functions for that purpose

onChangText = (value) => {
    this.loger(value)
}
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
0

i fix that by passing my function in body of an arrow function like below:

loger(value){
    console.log(value)
}
onChangeText(value){
    this.loger(value)
}

render() {

    return (
        <View style={{flex:1}}>
            <Ui 
                onChangeText={(value)=> this.onChangeText(value)}
            />
        </View>

    )
} 
amirhosein
  • 844
  • 9
  • 24