在React Native中检测View外部的点击

Nik*_*asv 5 modal-dialog reactjs react-native

如何检测视图外部的水龙头(视图是一个小的宽度和高度为200)。例如,我有一个自定义View(类似于模式),它的可见性由状态控制。但是,当在其外部单击时,由于未完成setState,因此未进行任何更改,我需要捕获用户(除了模式内部)无处不在。在React Native中怎么可能?

Sin*_*pcs 2

在模态周围使用 TouchableOpacity 并检查它是否处于按下状态。看这个例子。

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,
  }
});
Run Code Online (Sandbox Code Playgroud)

  • 这是一个很好的黑客,但我一直在寻找一些直接且非黑客的解决方案 (3认同)