原文地址,本文為原文不完全翻譯
布局與可變框
一個組件可以根據(jù)可變框計(jì)算來確定它的子組件的位置,可邊框的作用是用來適配不尺寸的手機(jī)屏幕局的.
你通常需要結(jié)合flexDirection, alignItems, 和 justifyContent
來實(shí)現(xiàn)想要的布局.
flexDirection
控制子組件排列方向,水平方向排列賦值row
,豎直方向排列賦值column
,默認(rèn)值為column
import React, { Component } from 'react';
import { AppRegistry, View } from 'react-native';
class FlexDirectionBasics extends Component{
render(){
return(
<View style={{flex:1,flexDirection: 'row'}}>
<View style={{flex:1, height: 50, backgroundColor: '#FF0000'}}/>
<View style={{flex:1, height: 50, backgroundColor: '#00FF00'}}/>
<View style={{flex:1, height: 50, backgroundColor: '#0000FF'}}/>
</View>
);
}
}
AppRegistry.registerComponent('FlexDirectionBasics', ()=>FlexDirectionBasics)
Paste_Image.png
Justify Content
這個屬性決定了子組件的分布方式,分布的方式有: flex-start(擠壓在其實(shí)位置), center(擠壓在中間), flex-end(擠壓在底部), space-around(邊緣分布均分), 和 space-between(均分并居中).
import React, { Component } from 'react';
import { AppRegistry, View } from 'react-native';
class justyContentDemo extends Component{
render(){
return(
//嘗試各種不同的值,加深理解(如:flex-start, center, flex-end)
<View style={{
flex: 1,
flexDirection: 'column',
justifyContent: 'space-between',
}}>
<View style={{width:50,height:50,backgroundColor:'#00FF00'}}/>
<View style={{width:50,height:50,backgroundColor:'#FF0000'}}/>
<View style={{width:50,height:50,backgroundColor:'#0000FF'}}/>
</View>
);
}
}
AppRegistry.registerComponent('justyContentDemo', ()=>justyContentDemo);
Paste_Image.png
Align Items
style中添加alignItems屬性可以影響子控件在父控件中的相對位置(是flex-start(頂部), center(居中), flex-end(底部), 還是拉伸填充(stretch)),假如子組件是水平排列就是影響豎直方向的相對位置,假如子組件是豎直排列影響的就是水平方向的相對位置,另外alignItems的優(yōu)先級是低于寬高的,假如發(fā)生沖突的話,寬高設(shè)置才是有效的,比如下面的例子中,子組件水平排列,設(shè)置alignItems : 'stretch'
, 但是因?yàn)樗{(lán)色與綠色的組件設(shè)置了height:50,所以無效,只有紅色的組件有效發(fā)生了拉伸填充
import React, { Component } from 'react';
import { AppRegistry, View } from 'react-native';
class AlignItemsBasics extends Component {
render(){
return(
<View style={{
flex:1,
flexDirection:'row',
justifyContent:'center',
alignItems: 'stretch'
}}>
<View style={{width: 50, backgroundColor: 'red'}} />
<View style={{width: 50, height: 50, backgroundColor: 'blue'}} />
<View style={{width: 50, height: 50, backgroundColor: 'green'}} />
</View>
)
}
}
AppRegistry.registerComponent('AlignItemsBasics', ()=>AlignItemsBasics);
Paste_Image.png