首页 > 解决方案 > 如何在 React Native android 上制作一个包裹相机可点击的 TouchableOpacity?

问题描述

我在 react-native TouchableOpacity 中渲染一个相机视图,如何让它可点击?

相同版本的代码在 iOS 上运行良好,touchableOpacity 是可点击的并产生正确的输出

<TouchableOpacity style={{width:'100%', height:300}} onPress={() =>alert("hey")}>
    <Camera 
        style={{ height: 300, width: '100%', display: this.state.camera }}  
        type={this.state.type} 
        autoFocus={'on'} 
        ratio={'4:3'}   
        focusDepth={0} 
        ref={(ref) => { this.camera = ref }}>
    </Camera>
</TouchableOpacity>

当我按下 TouchableOpacity 时,我希望输出是一个带有“嘿”的警报,而不是我在 android 上什么都没有,但我在 iOs 上得到一个“嘿”

标签: reactjsreact-nativetouchableopacity

解决方案


这是因为 TouchableOpacity 行为在 iO 和 Android 之间存在差异。一个快速的解决方法就是在 Android 中用 TouchableWithoutFeedback 替换 TouchableOpacity。这是一种方法:

const Touchable = Platform.select({ ios: TouchableOpacity, android: TouchableWithoutFeedback });

然后只需使用此常量来包装您的相机视图。

PS:确保你从 react-native 模块导入了 TouchableOpacity、TouchableWithoutFeedback 和 Platform。


推荐阅读