如何检测视图外部的点击(视图是一个小宽度和高度是200)。例如,我有一个自定义视图(类似于模态),它的可见性由状态控制。但是当点击它之外什么都没有改变,因为没有为此完成setState,我需要抓住用户点击除模态内部以外的任何地方。这怎么可能在React Native?
答案 0 :(得分:2)
在你的模态周围使用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,
}
});
答案 1 :(得分:0)
在TouchableOpacity / TouchableHighlight中包裹您的视图并添加onPress处理程序,以便您可以检测视图外的触摸。
类似的东西:
<TouchableOpacity onPress={() => {console.log('Touch outside view is detected')} }>
<View> Your View Goes Here </View>
</TouchableOpacity>
答案 2 :(得分:0)
<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/
我在这里找到了这些解决方案,希望对您有帮助