首页 > 解决方案 > Reat Native - 绝对位置不显示在视图顶部

问题描述

我使用 React Native 0.55,我想在 a 上显示一种图标,如下所示:http ://b3.ms/qpknagGre9BR

现在,我使用这个:

<View style={styles.cardContainer}>
    <Image source={iconPlayers} style={styles.iconTop} />
    <View style={styles.cardBox}>
        <View style={styles.container}>
            <Text style={styles.txtTitle}>
                My title
            </Text>
        </View>
    </View>
</View>

我的风格:

cardBox: {
    borderRadius: 20,
    backgroundColor: "#FFF",
    padding: 5,
    marginBottom: 10,
    borderColor: "#DDD",
    elevation: 4,
    paddingTop: 40,
},
cardContainer: {
    marginTop: 40,
},
container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center'
},
txtTitle: {
    color: "#000",
    textAlign: "center",
    fontWeight: "bold",
},
iconTop: {
    width: 60,
    height: 60,
    zIndex: 999,
    position: "absolute",
    top: -30,
    elevation: 4,
    alignSelf: "center",
},  

这很疯狂,因为现在它可以工作了,但是我有一个问题,我不能elevation: 4<Image />元素添加样式,我有一个警告

如果我删除elevation: 4,我的样式,图像将显示在cardBox后面。

我怎样才能在没有任何警告的情况下实现我想要的......?谢谢。

**编辑**

我将其包装<Image />在 a 中<View />,然后将elevation属性放入包装器中,并且它可以工作。

我以为elevation是用于 android 的 boxShadow,但它会影响 zIndex。

标签: react-native

解决方案


我正在小吃博览会中尝试您的代码,它使用最新的 react-native 版本(55.4)。将海拔应用于 Image 属性没有警告,它工作正常并且图像也在卡片上方。如果您的 react-native 版本发出警告,只需将其包装在 View 中并将提升应用于该 View。另外,请记住 zIndex 会受到视图高度的影响(仅限 Android)。由于您已将海拔高度:4 应用于卡片盒,因此您必须为您的图像组件提供高度 >= 4,否则它将在卡片盒下方绘制。

小吃示例:https ://snack.expo.io/B14UPA9Bm

您还可以通过更改组件的顺序来避免 Zindex,

// Render the image component after your card box this way you can avoid setting the zIndex
<View style={styles.cardContainer}>
    <View style={styles.cardBox}>
        <View style={styles.container}>
            <Text style={styles.txtTitle}>
                My title
            </Text>
        </View>
    </View>
    <Image source={iconPlayers} style={styles.iconTop} />
</View>

cardBox: {
    borderRadius: 20,
    backgroundColor: "#FFF",
    padding: 5,
    marginBottom: 10,
    borderColor: "#DDD",
    elevation: 4,
    paddingTop: 40,
},
cardContainer: {
    marginTop: 40,
},
container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center'
},
txtTitle: {
    color: "#000",
    textAlign: "center",
    fontWeight: "bold",
},
iconTop: {
    width: 60,
    height: 60,
    //zIndex: 999, not required now
    position: "absolute",
    top: -30,
    elevation: 4,
    alignSelf: "center",
}, 

检查并判断它是否适用于 Android 和 iOS。谢谢


推荐阅读