組件的高度與寬度決定了其在屏幕上顯示的尺寸。
指定寬高
最簡(jiǎn)單的給組件設(shè)定尺寸的方式就是在樣式中指定固定的width和height。React Native中的尺寸都是無(wú)單位的,表示的是與設(shè)備像素密度無(wú)關(guān)的邏輯像素點(diǎn)。
import React, { Component } from 'react';
import { View } from 'react-native';
export default class FixedDimensionsBasics extends Component{
render(){
return(
<View>
<View style={{width:50,height:50,backgroundColor:'powerblue'}}/>
<View style={{width:100,height:100,backgroundColor:'skyblue'}}/>
<View style={{width:150,height:150,backgroundColor:'steelblue'}}/>
</View>
);
}
}
運(yùn)行結(jié)果如圖

這樣給組件設(shè)置尺寸也是一種常見(jiàn)的模式,比如要求在不同尺寸的屏幕上都顯示成一樣的大小。
彈性(Flex)寬高
在組件樣式中使用flex可以使其在可利用的空間中動(dòng)態(tài)地?cái)U(kuò)張或收縮。一般而言我們會(huì)使用flex:1來(lái)指定某個(gè)組件擴(kuò)張以及撐滿所有剩余的空間。如果有多個(gè)并列的自組建使用了flex:1,則這些自組建會(huì)平分富容器中剩余的空間。如果這些并列的自組建的flex值不一樣,則誰(shuí)的值更大,誰(shuí)占據(jù)剩余空間的比例就更大(即占據(jù)剩余空間的比等于并列組件間flex值的比)。
組件能夠撐滿剩余空間的前提是其富容器的尺寸不為0。
如果父容器既沒(méi)有固定的width和height,也沒(méi)有設(shè)定flex,則父容器的尺寸為0。
其子組件如果使用了flex,也是無(wú)法顯示的。
import React, { Component } from 'react';
import { View } from 'react-native';
export default class FixedDimensionsBasics extends Component{
render(){
return(
<View style={{flex:1}}>
<View style={{flex:1,backgroundColor:'powerblue'}}/>
<View style={{flex:2,backgroundColor:'skyblue'}}/>
<View style={{flex:3,backgroundColor:'steelblue'}}/>
</View>
);
}
}
運(yùn)行結(jié)果如圖

當(dāng)你熟練掌握了如何控制組件的尺寸后,下一步就可以學(xué)習(xí)如何在屏幕上排列組件了。