似乎在使用position:absolute
时,元素无法使用justifyContent
或alignItems
居中。有一个使用marginLeft
的解决方法,但即使使用尺寸来检测设备的高度和宽度,也不会对所有设备显示相同的内容。
bottom: {
position: 'absolute',
justifyContent: 'center',
alignItems: 'center',
top: height*0.93,
marginLeft: width*0.18,
},
bottomNav: {
flexDirection: 'row',
},
将您想要居中的孩子包裹在视图中并使视图绝对。
<View style={{position: 'absolute', top: 0, left: 0, right: 0, bottom: 0, justifyContent: 'center', alignItems: 'center'}}>
<Text>Centered text</Text>
</View>
您可以通过提供左侧属性来设置绝对项目,其中设备的宽度除以2并减去您想要居中宽度的元素的一半。
例如,您的样式可能看起来像这样。
bottom: {
position: 'absolute',
left: (Dimensions.get('window').width / 2) - 25,
top: height*0.93,
}
用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
等属性。
真的很简单。使用width
和left
属性的百分比。例如:
logo : {
position: 'absolute',
top : 50,
left: '30%',
zIndex: 1,
width: '40%',
height: 150,
}
无论width
是什么,left
等于(100% - width)/2
你可以尝试代码
<View
style={{
alignItems: 'center',
justifyContent: 'center'
}}
>
<View
style={{
position: 'absolute',
margin: 'auto',
width: 50,
height: 50
}}
/>
</View>