React Native中判断点击元素是否为父元素的后代
React Native实现点击View外部移除、点击子元素不触发的效果
要实现的效果:点击粉色盒子的外部区域时,将盒子从屏幕移除;点击盒子内部的任意子元素或盒子本身时,不执行移除操作。
解决方案代码
import * as React from 'react'; import { View, StyleSheet, Pressable } from 'react-native'; export default function App() { const [showBox, setShowBox] = React.useState(true); // 点击外部区域时隐藏盒子 const handleOutsidePress = () => { setShowBox(false); }; // 阻止事件冒泡,避免触发外部点击逻辑 const handleInnerPress = (e) => { e.stopPropagation(); }; return ( <Pressable style={styles.container} onPress={handleOutsidePress}> {showBox && ( <View style={styles.box} onPress={handleInnerPress}> <View style={styles.child} onPress={handleInnerPress}></View> <View style={styles.child} onPress={handleInnerPress}></View> </View> )} </Pressable> ); } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center'}, box: {backgroundColor: 'pink', width: 200, aspectRatio: '1/1', justifyContent: "space-around", paddingHorizontal: 20}, child: {backgroundColor: "indigo", height: 40} });
关键逻辑说明
- 使用
useState钩子维护盒子的显示状态showBox,初始值设为true让盒子默认显示 - 最外层使用
Pressable组件包裹,绑定handleOutsidePress函数,点击此区域(盒子外部)时将showBox设为false,隐藏盒子 - 给粉色盒子和内部所有子元素绑定
handleInnerPress函数,通过e.stopPropagation()阻止事件向上冒泡到外层的Pressable,这样点击盒子内部时不会触发外部移除逻辑
内容的提问来源于stack exchange,提问作者Joe
相关产品推荐
相关产品推荐

