React Native: can't call a parent method from child

Viewed 2649

I have this function in parent component, and I am trying to call this method/function in child , like so:

buttonPressed = () => {
  console.log('button pressed')
}

<childComp ref={ref => this.feedback = ref}
           onPress={this.buttonPressed}
/>

in child:

<Animated.View>
  ...   // other views
  <View>
    <TouchableOpacity onPress={this.props.buttonPressed}> // calling here
     ...
    </TouchableOpacity>

  </View>
</Animated.View>

No matter what I tried , it didn't work.

2 Answers

you are passing onPress prop to child and calling buttonPressed in child. it should be like this :

<Animated.View>
  ...   // other views
  <View>
    <TouchableOpacity onPress={this.props.onPress}> // calling here
     ...
    </TouchableOpacity>

  </View>
</Animated.View>

I think that in child component you should call to this.props.onPress(), because the name of the property thar you are passing is onPress. Also, don't forget to put () when you want to call the function. So it should be:

<Animated.View>
  ...   // other views
  <View>
    <TouchableOpacity onPress={this.props.onPress()}> // calling here
     ...
    </TouchableOpacity>

  </View>
</Animated.View>
Related