分類: React Native
說到佈局,不論是Android還是iOS還是web前端,都有涉及到,React Native中也有佈局,主要採用了類似css中的flexbox佈局,不過這種佈局跟css中的flexbox佈局稍微有點不同,下面就記錄在React Native中使用flexbox佈局的方法,主要涉及到如下幾個屬性:
1、flex
2、flexDirection
3、alignSelf
4、alignItems
5、justifyContent
還有其他的一些屬性,可以參考React Native中文文檔:http://wiki.jikexueyuan.com/project/react-native/flexbox.html,或者css中有關flexbox屬性的文檔:http://www.runoob.com/cssref/css3-pr-align-items.html
下面就來一一解釋上面幾個屬性:
flex屬性
class Test extends Component {
render() {
return (
<View style={styles.container}>
<View style={styles.child1}>
</View>
<View style={styles.child2}>
</View>
<View style={styles.child3}>
</View>
</View>
);
}
}
const styles = {
container: {
flex: 1,
flexDirection: 'column', //子元素垂直排列,默認是垂直排列的
},
child1: {
flex: 1,
backgroundColor: '#aa0000',
},
child2: {
flex: 1,
backgroundColor: '#aaaa00',
},
child3: {
flex: 2,
backgroundColor: '#0000aa',
}
};
在上面的代碼中,分別爲child1, child2, child3設置了flex屬性爲1, 1, 2,代表這三個元素在垂直方向上是按1:1:2的比例排列的,在手機上顯示出來的效果如下圖:flexDirection屬性
alignSelf屬性
class Test extends Component {
render() {
return (
<View style={styles.container}>
<Text style={[styles.block1, styles.text]}>alignSelf: 'flex-start'</Text>
<Text style={[styles.block2, styles.text]}>alignSelf: 'flex-end'</Text>
<Text style={[styles.block3, styles.text]}>alignSelf: 'center'</Text>
<Text style={[styles.block4, styles.text]}>alignSelf: 'auto'</Text>
<Text style={[styles.block5, styles.text]}>alignSelf: 'stretch'</Text>
</View>
);
}
}
const styles = {
container: {
flex: 1,
},
text: {
fontSize: 13,
color: '#ff0000',
marginTop: 10,
},
block1: {
width: 150,
height: 40,
backgroundColor: '#6699ff',
alignSelf: 'flex-start',
},
block2: {
width: 150,
height: 40,
backgroundColor: '#6699ff',
alignSelf: 'flex-end',
},
block3: {
width: 150,
height: 40,
backgroundColor: '#6699ff',
alignSelf: 'center',
},
block4: {
width: 150,
height: 40,
backgroundColor: '#6699ff',
alignSelf: 'auto',
},
block5: {
height: 40,
backgroundColor: '#6699ff',
alignSelf: 'stretch',
}
};
上面的代碼在手機上運行的效果如下圖:alignItems屬性
justifyContent屬性
class Test extends Component {
render() {
return (
<View style={styles.container}>
<Text style={[styles.block, styles.text]}></Text>
<Text style={[styles.block, styles.text]}></Text>
<Text style={[styles.block, styles.text]}></Text>
<Text style={[styles.block, styles.text]}></Text>
<Text style={[styles.block, styles.text]}></Text>
</View>
);
}
}
const styles = {
container: {
flex: 1,
justifyContent: 'flex-start',
},
text: {
fontSize: 13,
color: '#ff0000',
marginTop: 10,
},
block: {
width: 150,
height: 40,
backgroundColor: '#6699ff',
}
};
以上代碼在手機上的運行效果如下圖:如果將container中的justifyContent改爲flex-end,則運行效果如下: