Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onPress in TouchableOpacity doesn't trigger

Tags:

react-native

I need your help! My goal is to change the style of my button after I clicked it! I heard about direct manipulation and I decided to give it a try. Now I don't know why but the onPress inside my TouchableOpacity doesn't work. Here is the code:

<TouchableOpacity onPress={() => this.changeStyle}>
   <TouchableHighlight style={styles.answer} ref="answer1">
      <Text ...> Some Text </Text>
   </TouchableHighlight>
</TouchableOpacity>

And here is my changeStyle function:

changeStyle() {
   this.refs['answer1'].setNativeProps({
      style: { backgroundColor: "#13a88a"}
   });
}

Now i don't know why but the 'onPress' is never triggered. Thank you for your answers!

like image 372
Eren.Miracle- Avatar asked Mar 09 '23 19:03

Eren.Miracle-


2 Answers

If you want to execute the function by using 'this.changeStyle`, write your onPress like so:

<TouchableOpacity onPress={this.changeStyle}/>

If you're going to pass a function within the onPress prop that executes this.changeStyle write your onPress like so:

<TouchableOpacity onPress={() => this.changeStyle()}/>

P.S: Why do you have <TouchableHighlight/> inside a <TouchableOpacity/>? Just use one and add the onPress prop on it.

like image 170
Ray Avatar answered Apr 30 '23 04:04

Ray


You need to import TouchableOpacity from react-native instead of importing it from react-native-gesture-handler. The version in react-native-gesture-handler is 100% broken. The version in react-native works.

like image 26
Andrew Koster Avatar answered Apr 30 '23 04:04

Andrew Koster