React Native绝对定位水平中心

问题描述 投票:61回答:6

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

  bottom: {
    position: 'absolute',
    justifyContent: 'center',
    alignItems: 'center',
    top: height*0.93,
    marginLeft: width*0.18,
  },
  bottomNav: {
    flexDirection: 'row',
  },
position react-native flexbox absolute
6个回答
142
投票

将您想要居中的孩子包裹在视图中并使视图绝对。

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

34
投票

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

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

这是一个示例(请注意,徽标父级是一个位置为相对的视图)

enter image description here


10
投票

您可以通过提供左侧属性来设置绝对项目,其中设备的宽度除以2并减去您想要居中宽度的元素的一半。

例如,您的样式可能看起来像这样。

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

2
投票

View创建一个全宽的alignItems: "center"然后插入所需的孩子。

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等属性。


0
投票

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

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

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


-1
投票

你可以尝试代码

<View
    style={{
      alignItems: 'center',
      justifyContent: 'center'
    }}
  >
    <View
      style={{
        position: 'absolute',
        margin: 'auto',
        width: 50,
        height: 50
      }}
    />
  </View>
© www.soinside.com 2019 - 2024. All rights reserved.