在 React Native 中检测视图外部的点击

IT技术 reactjs react-native modal-dialog
2021-04-30 14:04:58

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

3个回答

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

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,
  }
});
<View
  onStartShouldSetResponder={evt => {
    evt.persist();
    if (this.childrenIds && this.childrenIds.length) {
      if (this.childrenIds.includes(evt.target)) {
        return;
      }
      console.log('Tapped outside');
    }
  }} 
>
  // popover view - we want the user to be able to tap inside here
  <View ref={component => {
   this.childrenIds = component._children[0]._children.map(el => el._nativeTag) 
  }}>
    <View>
      <Text>Option 1</Text>
      <Text>Option 2</Text>
    </View>
  </View>

  // other view - we want the popover to close when this view is tapped
  <View>
    <Text>
      Tapping in this view will trigger the console log, but tapping inside the 
      view above will not.
    </Text>
  </View>
</View>

https://www.jaygould.co.uk/2019-05-09-detecting-tap-outside-element-react-native/

我在这里找到了这些解决方案,希望它有帮助

将您的视图包裹在 TouchableOpacity/TouchableHighlight 中并添加 onPress 处理程序,以便您可以检测到视图外的触摸。

就像是 :

<TouchableOpacity onPress={() => {console.log('Touch outside view is detected')} }>
   <View> Your View Goes Here </View>
</TouchableOpacity>