zIndex 在 React Native 项目中无效。

32

我正在尝试在React Native中将一张卡片显示在另一张卡片的上方,并为顶部卡片设置zIndex = 1,底部卡片设置zIndex = 0,并将它们放置在以下视图中:

<View style={{paddingVertical: MARGIN_1, justifyContent: 'center'}}>
  {this.props.subscribed ? (
    <CardSubscribe
      style={{zIndex: 2}}
    />
  ) : (null)}
  {this._renderTextItems()}
</View> 

然而,两张卡片之间没有重叠。底部卡片在顶部卡片之后开始:

enter image description here

我还尝试使用检查工具进行调试,它显示顶部卡片具有 zIndex = 1 属性:

enter image description here

而底部卡片具有 zIndex = 0 属性:

enter image description here

我还尝试将顶部卡片放在底部卡片之后,但它只显示在底部卡片下面,好像 zIndex 没起作用。我应该怎么解决这个问题?

2个回答

63

z-index在IOS上工作正常。但在Android上你会遇到问题。在Android上,z-index不起作用,您需要使用elevation。但请不要忘记添加z-index。

<TouchableOpacity
              style={{
                alignSelf: 'center',
                position: 'absolute',
                right: 10,
                top: 10,
                zIndex: 15,
                elevation: (Platform.OS === 'android') ? 50 : 0
              }}
              onPress={() => {}}
            >
              <Image
                source={require('dummy.png')}
              />
            </TouchableOpacity>

7
"elevation" 解决了我的问题。谢谢。 - Flagship1442
1
非常感谢!我一直在为这个问题苦苦挣扎,从未想到提升属性可以解决它。非常感谢。 - luuchorocha
1
直到看到这个,我才找到了方向。非常感谢! - Charitha Goonewardena
1
谢谢你啊!有点难以猜测呢! - Syed Arsalan Kazmi
高度调整对我没用..只有在安卓上重新排序才有效。 如果我想让视图2覆盖视图1(在视图1的顶部),那么: <View style={styles.view1}></View><View style={styles.view2} ></View> - Danny Michaeli

23
React Native中,默认情况下我们有position: relative。如果你想正确使用zIndex,你可能需要添加position: 'absolute',以便它们重叠,就像你在使用案例中描述的那样。
例如:
<View style={{flex: 1}}>
               <View style={{width: 200, height: 200, zIndex: 1, position: 'absolute', backgroundColor: 'red'}} />
               <View style={{width: 200, height: 200, zIndex: 2, position: 'absolute', backgroundColor: 'blue'}} />
 </View>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接