React Native 绝对定位水平居中

React Native absolute positioning horizontal centre

使用 position:absolute 时,似乎无法使用 justifyContentalignItems 使元素居中。有一个解决方法可以使用 marginLeft,但即使使用尺寸来检测设备的高度和宽度,也不会对所有设备显示相同的内容。

  bottom: {
    position: 'absolute',
    justifyContent: 'center',
    alignItems: 'center',
    top: height*0.93,
    marginLeft: width*0.18,
  },
  bottomNav: {
    flexDirection: 'row',
  },

将你想要居中的 child 包裹在一个 View 中,并使 View 成为绝对的。

<View style={{position: 'absolute', top: 0, left: 0, right: 0, bottom: 0, justifyContent: 'center', alignItems: 'center'}}>
  <Text>Centered text</Text>
</View>

您可以通过向左 属性 提供设备的宽度除以二,然后减去您想要居中宽度的元素的一半,来居中绝对项目。

例如,您的风格可能是这样的。

bottom: {
    position: 'absolute',
    left: (Dimensions.get('window').width / 2) - 25,
    top: height*0.93,
}

你可以试试代码

<View
    style={{
      alignItems: 'center',
      justifyContent: 'center'
    }}
  >
    <View
      style={{
        position: 'absolute',
        margin: 'auto',
        width: 50,
        height: 50
      }}
    />
  </View>

如果你想让一个元素本身居中,你可以使用 alignSelf:

logoImg: {
    position: 'absolute',
    alignSelf: 'center',
    bottom: '-5%'
}

这是一个示例(请注意,徽标父项是具有 position: relative 的视图)

真的很简单。对 widthleft 属性使用百分比。例如:

logo : {
  position: 'absolute',
  top : 50,
  left: '30%',
  zIndex: 1,
  width: '40%',
  height: 150,
}

无论 width 是什么,left 都等于 (100% - width)/2

alignItems: "center" 创建一个 full-width View 然后在里面插入想要的 children。

import React from "react";
import {View} from "react-native";

export default class AbsoluteComponent extends React.Component {
  render(){
    return(
     <View style={{position: "absolute", left: 0, right: 0, alignItems: "center"}}>
      {this.props.children}
     </View>    
    )
  }
}

您可以为底部对齐的组件添加 bottom: 30 等属性。

<View style={{...StyleSheet.absoluteFillObject, justifyContent: 'center', alignItems: 'center'}}>
    <Text>CENTERD TEXT</Text>
</View>

并添加这个

import {StyleSheet} from 'react-native';

好吧,我会用这种方式使绝对视图居中

  <View style={{ position: 'absolute', left: '50%', marginLeft: -22 }}>
           <View style={{ position: 'absolute', width: 44, height: 44}}>
             <Ionicons name="close" color="#4775f2" size={32} />
           </View>
   </View>

请注意,在包装图标容器的视图中,我使用的是 left: 50% 并且 marginLeft 是特殊的,因为您需要准确地放置子项的中间宽度并将其变为负数,在本例中为44如你所见,仅此而已