React Native文本被元素遮挡,设置zIndex仍无法上层显示如何解决?
问题根因
React Native的zIndex仅在同一个父容器的直接子元素之间生效:
- 文本所在的带
marginTop:150的<View>和存放Square的<View>是<SafeAreaView>的两个直接同级子元素 - 内部Text设置的
zIndex仅在它自身的父View范围内生效,无法影响与另一个同级父容器内Square的层级关系 - 安卓端
elevation属性的层级优先级高于zIndex,未显式设置时默认值也可能导致层级异常
解决方案
方案1:调整同级父容器的zIndex(全平台兼容,推荐)
给存放文本的父容器设置更高的层级,修改后的主业务代码如下:
<View style={{flex: 1, padding: 0}}> {isLoading ? ( <Text>Loading...</Text> ) : ( <SafeAreaView style={{flex: 1, backgroundColor: '#8af542'}}> <View style={{ marginTop: 150, alignItems: 'center', justifyContent: 'center', zIndex: 2, // 新增,层级高于方块容器 elevation: 2, // 新增,适配安卓端层级规则 }}> <Text>TEST</Text> <Text style={{ position: 'absolute', top: 140, }}> TEXT HERE </Text> </View> <View style={{ flex: 1, justifyContent: 'flex-end', marginBottom: windowHeight * -0.05, zIndex: 1, // 新增,层级低于文本容器 elevation: 1, // 新增,适配安卓端层级规则 }}> <Square></Square> </View> </SafeAreaView> )} </View>
方案2:直接降低Square的层级
如果不想修改父容器结构,直接调整Square的样式属性即可,修改后的样式代码如下:
const styles = StyleSheet.create({ centerItems: { justifyContent: 'center', alignItems: 'center', }, square: { width: windowWidth, height: windowHeight * 0.6, backgroundColor: 'white', flex: 1, justifyContent: 'flex-end', marginBottom: windowHeight * -0.05, position: 'absolute', zIndex: 0, // 新增,层级低于文本 elevation: 0, // 新增,取消安卓端默认elevation优先级 }, });
同时保留文本的zIndex: 1、elevation: 1属性即可生效。
内容的提问来源于stack exchange,提问作者PhpCoder223
相关产品推荐
相关产品推荐

