参考:
一、概述
在React Native中,flexbox定位和position定位可以同时使用,
同时生效(关于flexbox定位的相关知识请自行查阅资料,这里不再赘述)。
position有两个取值:relative(默认值)和absolute。
二、relative——相对定位
以元素本来的位置为基准进行偏移。
示例:
import React, {Component} from 'react';
import {
Platform,
StyleSheet,
Text,
View,
TextInput,
} from 'react-native';
export default class Test extends Component {
render() {
return (
<View style={styles.container}>
<View style={styles.p1}/>
<View style={styles.p2}/>
<View style={styles.p3}/>
<View style={styles.p4}/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'column',
alignItems: 'center',
backgroundColor: '#33ffff',
},
p1: {
width: 50,
height: 50,
backgroundColor: 'red',
},
p2: {
width: 50,
height: 50,
backgroundColor: 'yellow',
},
p3: {
width: 50,
height: 50,
backgroundColor: 'blue',
},
p4: {
width: 50,
height: 50,
backgroundColor: '#666',
position: 'relative',
left: 50,
top: 50,
},
});
- 灰色方块本来的位置应该是靠在蓝色方块的下方并与蓝色方块左右对齐,
- 通过position: ‘relative’,left: 50,top: 50使得灰色方块以其本来的位置为基准,
- 向右、向下分别偏移了50个单位,效果如上图所示。
三、absolute——绝对定位
以父元素的边框为基准进行偏移。
示例:
import React, {Component} from 'react';
import {
Platform,
StyleSheet,
Text,
View,
TextInput,
} from 'react-native';
export default class Test extends Component {
render() {
return (
<View style={styles.container}>
<View style={styles.p1}/>
<View style={styles.p2}/>
<View style={styles.p3}/>
<View style={styles.p4}/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'column',
backgroundColor: '#33ffff',
},
p1: {
width: 50,
height: 50,
backgroundColor: 'red',
position: 'absolute',
left: 50,
top: 50,
},
p2: {
width: 50,
height: 50,
backgroundColor: 'yellow',
position: 'absolute',
right: 50,
bottom: 50,
},
p3: {
width: 50,
height: 50,
backgroundColor: 'blue',
position: 'absolute',
bottom: 50,
},
p4: {
width: 50,
height: 50,
backgroundColor: '#666',
position: 'absolute',
bottom: 50,
alignSelf: 'center',
},
});
- 红色方块:以父元素的左边框、上边框为基准,分别向右、向下偏移了50个单位。
- 黄色方块:以父元素的右边框、下边框为基准,分别向左、向上偏移了50个单位。
- 蓝色方块:以父元素的下边框为基准,向上偏移了50个单位。
- 灰色方块:以父元素的下边框为基准,向上偏移了50个单位。左右位置由flexbox定位决定,即水平居中。