Reactjs 在react native中检测视图外部的点击
如何检测视图外部的点击(视图是一个小视图,宽度和高度为200)。例如,我有一个自定义视图(类似于模态),它的可见性由状态控制。但是当点击它的外部时,没有任何改变,因为没有设置状态,我需要捕捉用户点击除模式内部之外的任何地方。在React Native中如何实现这一点?在模态周围使用TouchableOpacity,并检查它是否处于按下状态。看看这个例子Reactjs 在react native中检测视图外部的点击,reactjs,react-native,modal-dialog,Reactjs,React Native,Modal Dialog,如何检测视图外部的点击(视图是一个小视图,宽度和高度为200)。例如,我有一个自定义视图(类似于模态),它的可见性由状态控制。但是当点击它的外部时,没有任何改变,因为没有设置状态,我需要捕捉用户点击除模式内部之外的任何地方。在React Native中如何实现这一点?在模态周围使用TouchableOpacity,并检查它是否处于按下状态。看看这个例子 const { opacity, open, scale, children,offset } = this.state; let contai
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,
}
});
const{opacity,open,scale,children,offset}=this.state;
让containerStyles=[styles.absolute,styles.container,this.props.containerStyle];
让backStyle={flex:1,不透明,backgroundColor:this.props.overlybackground};
{儿童}
const styles=StyleSheet.create({
绝对:{
位置:'绝对',
排名:0,
左:0,,
右:0,,
底部:0,
背景颜色:“透明”
},
容器:{
为内容辩护:“中心”,
标高:10,
}
});
将视图包装在TouchableOpacity/TouchableHighlight中,并添加onPress处理程序,以便您可以检测视图外的触摸
比如:
<TouchableOpacity onPress={() => {console.log('Touch outside view is detected')} }>
<View> Your View Goes Here </View>
</TouchableOpacity>
{console.log('检测到触摸外部视图')}>
你的观点是这样的
{
evt.persist();
if(this.childrenIds&&this.childrenIds.length){
if(此.childrenIds.includes(evt.target)){
返回;
}
console.log('Tapped out');
}
}}
>
//popover视图-我们希望用户能够点击这里的内部
{
this.childrenIds=component.\u children[0]。\u children.map(el=>el.\u nativeTag)
}}>
选择1
选择2
//其他视图-点击此视图时,我们希望弹出窗口关闭
在此视图中点击将触发控制台日志,但在
上面的视图将不可用。
我在这里找到了这些解决方案,希望能有所帮助这不会起作用,因为代码中的“TouchableOpacity”也会检测进入实际视图的触摸。要解决这个问题,你必须使用绝对风格(见另一个答案)。这是一个很好的技巧,但我一直在寻找一些直接的、非黑客的解决方案。我知道你问这个问题已经很久了。将此链接放在此处,供未来开发人员询问与您相同的问题。由于缺乏替代方案,该方法使用内部的私有道具