programing

기본적으로 반응하는 보기 외부 탭 탐지

prostudy 2022. 4. 5. 22:30
반응형

기본적으로 반응하는 보기 외부 탭 탐지

뷰의 외부 탭 탐지 방법(뷰는 작은 한 폭과 높이 200).예를 들어, 나는 (모달과 같은) 사용자 정의 뷰를 가지고 있고, 그것의 가시성은 주(州)에 의해 제어된다.하지만 setState가 실행되지 않았기 때문에 그 외부를 클릭할 때, 나는 모달 내부를 제외한 모든 곳에서 사용자들을 도청하는 것을 포착해야 한다.React Native에서는 어떻게 그것이 가능한가?

모달 주위에 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 Handler를 추가하십시오.

다음과 같은 경우:

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

참조URL: https://stackoverflow.com/questions/46783104/detect-tap-on-the-outside-of-the-view-in-react-native

반응형