简体   繁体   English

TouchableOpacity onPress 不适用于 Android

[英]TouchableOpacity onPress not working on Android

I have 3 simple react components-我有 3 个简单的反应组件-

First the actual view(let us name this screen A)-首先是实际视图(让我们将此屏幕命名为 A)-

return(
    <ImageBackground
    ...
    >
       <ScrollView>


          <ChildButton
            onPress={this.someFunction.bind(this)}
           />

       </ScrollView>
    </ImageBackground>
)

Then there is the ChildButton component---然后是 ChildButton 组件---

    return(
    <ChildButton>
       <Button
         style={...someStyleObject}
         onPress={this.props.onPress}
        >

       </Button>

    </ChildButton>
)

and then there is Button component ---然后是按钮组件---

return (
<TouchableOpacity
  onPress={this.props.onPress}
 >
    {this.props.children}
</TouchableOpacity>

)

The main problem here is my onPress is not getting called from screen A, only on Android.这里的主要问题是我的 onPress 没有从屏幕 A 被调用,只有在 Android 上。 It is working fine on iOS.它在 iOS 上运行良好。 What are the possible causes here?这里可能的原因是什么?

Note: I've put consoles inside ChildButton and Button component and they are not getting printed.注意:我已经将控制台放在 ChildButton 和 Button 组件中,但它们没有被打印出来。

I ran into this issue when I accidentally imported TouchableOpacity from "react-native-gesture-handler" instead of from "react-native".当我不小心从“react-native-gesture-handler”而不是“react-native”导入TouchableOpacity时,我遇到了这个问题。 If this is the case for you, change so TouchableOpacity is imported from "react-native" and remove the import from "react-native-gesture-handler" and it should work!如果是这种情况,请更改为从“react-native”导入TouchableOpacity并从“react-native-gesture-handler”中删除导入,它应该可以工作!

I also ran into this issue when I inherited a RN project in progress.当我继承一个正在进行的 RN 项目时,我也遇到了这个问题。 I didn't realize we had this "react-native-gesture-handler" package installed and accidentally let VS Code auto import it.我没有意识到我们安装了这个“react-native-gesture-handler”包并且不小心让 VS Code 自动导入它。

Always check your imports!始终检查您的进口! :) :)

import {TouchableOpacity} from 'react-native' 
works fine in both android and iOS


import {TouchableOpacity} from 'react-native-gesture-handler'
Does not work in android, but works in iOS.

So better to user react-native imports.所以对用户反应原生导入更好。

onPress event is not calling in android if TouchableOpacity imported from react-native-gesture-handler.如果 TouchableOpacity 从 react-native-gesture-handler 导入,则 onPress 事件不会在 android 中调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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