在 React Native 中使用绝对位置将图像居中

问题描述 投票:0回答:1

我是 React 新手,正在尝试将

<Image />
组件置于更大的
<View />
中,如下所示:

import { Image, View } from 'react-native';

<View
  style={{
    width: 48,
    height: 48,
    alignSelf: "center",
    justifyContent: "center",
    alignItems: "center",
    position: "relative",
  }}
>
  <Image
    style={{
      width: 32,
      height: 32,
      position: "absolute",
      top: 0,
      left: 0,
      right: 0,
      bottom: 0,
      margin: "auto",
    }}
    source={spinner}
  />
</View>;

但它不是居中,而是位于

<View />
内的左上角。

上面的 CSS 可以在 HTML 中使用,但是对于 React Native 我缺少什么?顺便说一句,我必须使用图像的绝对位置来覆盖

<View />
内的其他组件。

谢谢你,

css react-native
1个回答
0
投票

将其与绝对值一起添加到您的子元素上将解决该问题。 顶部:“50%”, 左:“50%”, 变换:“翻译(-50%,-50%)”

<SafeAreaView>
      <View
          style={{
            width: 48,
            height: 48,
            alignSelf: "center",
            justifyContent: "center",
            alignItems: "center",
            position: "relative",
            borderColor: '#000',
            borderWidth: 1
          }}
        >
          <Image
            style={{
              width: 32,
              height: 32,
              position: "absolute",
              top: '50%',
              left: '50%',
              transform: "translate(-50%, -50%)"
            }}
            source={{uri: 'image_url_here'}}
          />
        </View>
    </SafeAreaView>
© www.soinside.com 2019 - 2024. All rights reserved.