使用style變量的方式設(shè)置樣式
-
實(shí)際開發(fā)中組件的樣式會(huì)越來越復(fù)雜,我們建議使用StyleSheet.create來集中定義組件的樣式。比如像下面這樣:
e.g.: const styles = StyleSheet.create({ bigBlue: { color: 'blue' , fontWeight: 'blod' , fontSize: 30, }, red: { color: 'red', } })
常見的做法是按順序聲明和使用style屬性,以借鑒CSS中的“層疊”做法(即后聲明的屬性會(huì)覆蓋先聲明的同名屬性)。
- 指定寬高的屬性:width,height
- 指定背景顏色屬性:backgroundColor
e.g.: --- 使用內(nèi)聯(lián)樣式表構(gòu)建樣式
<View style={{width: 50, height: 50, backgroundColor: 'powderblue'}} /> - 彈性寬高布局:在組件樣式中使用flex可以使其在可利用的空間中動(dòng)態(tài)地?cái)U(kuò)張或收縮。一般而言我們會(huì)使用flex:1來指定某個(gè)組件擴(kuò)張以撐滿所有剩余的空間。如果有多個(gè)并列的子組件使用了flex:1,則這些子組件會(huì)平分父容器中剩余的空間。如果這些并列的子組件的flex值不一樣,則誰的值更大,誰占據(jù)剩余空間的比例就更大(即占據(jù)剩余空間的比等于并列組件間flex值的比)。
注: 組件能夠撐滿剩余空間的前提是其父容器的尺寸不為零。如果父容器既沒有固定的width和height,也沒有設(shè)定flex,則父容器的尺寸為零。其子組件如果使用了flex,也是無法顯示的。
e.g.:
<View style={{flex: 1}}>
<View style={{flex: 1, backgroundColor: 'powderblue'}} />
<View style={{flex: 2, backgroundColor: 'skyblue'}} />
<View style={{flex: 3, backgroundColor: 'steelblue'}} />
</View>
關(guān)于 Flexbox 的相關(guān)布局
- flexDirection : 默認(rèn)是豎直軸方向
e.g.(轉(zhuǎn)化為水平方向布局): style={{flex: 1, flexDirection: 'row'} - Justify Content (子元素延主軸的排列方式)
flex-start、center、flex-end、space-around以及space-between
e.g. :
<View style={{
flex: 1,
flexDirection: 'column',
justifyContent: 'space-between',
}}>
<View style={{width: 50, height: 50, backgroundColor: 'powderblue'}} />
<View style={{width: 50, height: 50, backgroundColor: 'skyblue'}} />
<View style={{width: 50, height: 50, backgroundColor: 'steelblue'}} />
</View> - Align Items (子元素延次軸的排列方式)
在組件的style中指定alignItems可以決定其子元素沿著次軸(與主軸垂直的軸,比如若主軸方
向?yàn)閞ow,則次軸方向?yàn)閏olumn)的排列方式。子元素是應(yīng)該靠近次軸的起始端還是末尾段分布呢?
亦或應(yīng)該均勻分布?對(duì)應(yīng)的這些可選項(xiàng)有:flex-start、center、flex-end以及stretch。
注:要使stretch選項(xiàng)生效的話,子元素在次軸方向上不能有固定的尺寸。以下面的代碼為例:只有將子元素樣式中的width: 50去掉之后,alignItems: 'stretch'才能生效。