简体   繁体   中英

React Native TouchableHighlight onPress not working

I have tried everything to make this work. I have read all the answers and it never works for me. I am completely out of ideas.

Here is the function I am trying to call:

function handlePress() {
    console.log('test');
}

Here is what I have tried:

This one does nothing:

<TouchableHighlight
    onPress={() => { alert('You tapped the button!') }}>
  <Text style={ styles.sendButton }>Test Touch</Text>
</TouchableHighlight>

This one triggers without me doing anything:

<TouchableHighlight
    onPress={alert('You tapped the button!')}>
  <Text style={ styles.sendButton }>Test Touch</Text>
</TouchableHighlight>

This one triggers without me doing anything:

<TouchableHighlight
    onPress={handlePress()}>
  <Text style={ styles.sendButton }>Test Touch</Text>
</TouchableHighlight>

This one does nothing:

<TouchableHighlight
    onPress={() => {() => handlePress()}}>
  <Text style={ styles.sendButton }>Test Touch</Text>
</TouchableHighlight>

This one does nothing:

    <TouchableHighlight
    onPress={() => handlePress()}>
  <Text style={ styles.sendButton }>Test Touch</Text>
</TouchableHighlight>

This one does nothing:

<TouchableHighlight
    onPress={handlePress}>
  <Text style={ styles.sendButton }>Test Touch</Text>
</TouchableHighlight>

Can anyone help?

  <TouchableHighlight style={{backgroundColor: 'yellow'}}
   onPress={()=> {alert('You tapped the button!')}}>
  <Text style={{color: '#000', textAlign: "center", fontSize: 40}}>Test Touch</Text>
  </TouchableHighlight>

I just tried this one myself and it works. I didn't see a difference with your code, so I copied yours, tried and it worked. Are you sure you didn't mess up the CSS style making it unreachable?

I would isolate the button in some screen and try it alone.

I had done everything the same as you have. Only I have heavily relied on auto-import of VS code that TouchableHighlight was auto imported from react-native-gesture-handler rather it should be imported from react-native lib.

I changed it to react-native and it is working fine.

Wrong

在此处输入图像描述

Corrected

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM