在 React Native 中检测视图外部的点击 [英] Detect tap on the outside of the View in react native

查看:93
本文介绍了在 React Native 中检测视图外部的点击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检测 View 外部的点击(View 是一个小的宽度和高度为 200 的).例如,我有一个自定义视图(就像一个模态),它的可见性由状态控制.但是当点击它的外部时,没有任何改变,因为没有为此完成 setState,我需要捕捉用户点击除模态内部之外的任何地方.这在 React Native 中怎么可能?

How to detect tap on the outside of the View(View is a small one width and height are 200). For example, I have a custom View(which is like a modal) and it's visibility is controlled by state. But when clicking outside of it nothing is changed because there is no setState done for that, I need to catch users tap everywhere except inside the modal. How is that possible in React Native?

推荐答案

在模态周围使用 TouchableOpacity 并检查它是否处于 onPress.看看这个例子.

use a TouchableOpacity around your modal and check it's onPress. Look at this example.

const { opacity, open, scale, children,offset } = this.state;
let containerStyles = [ styles.absolute, styles.container, this.props.containerStyle ];
let backStyle= { flex: 1, opacity, backgroundColor: this.props.overlayBackground };

<View
    pointerEvents={open ? 'auto' : 'none'}
    style={containerStyles}>
    <TouchableOpacity
      style={styles.absolute}
      disabled={!this.props.closeOnTouchOutside}
      onPress={this.close.bind(this)}
      activeOpacity={0.75}>
      <Animated.View style={backStyle}/>
    </TouchableOpacity>
    <Animated.View>
      {children}
    </Animated.View>
  </View>

const styles = StyleSheet.create({
  absolute: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    backgroundColor: 'transparent'
  },
  container: {
    justifyContent: 'center',
    elevation: 10,
  }
});

这篇关于在 React Native 中检测视图外部的点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆