組件的高度和寬度決定了其在屏幕上顯示的尺寸谓传。
指定寬高
最簡單的給組件設(shè)定尺寸的方式就是在樣式中指定固定的 width 和 height蜈项。
React Native中的尺寸都是無單位的,表示的是與設(shè)備像素密度無關(guān)的邏輯像素點续挟。
import React, { Component } from 'react';
import {
AppRegistry,
View
} from 'react-native';
class MyApp extends Component {
render() {
return (
<View>
<View style={{width: 50, height: 50,backgroundColor:'powderblue'}} />
<View style={{width: 100,height:100,backgroundColor:'skyblue'}} />
<View style={{width: 150,height:150,backgroundColor:'steelblue'}} />
</View>
);
}
}
// 注冊應(yīng)用(registerComponent)后才能正確渲染
// 注意:只把應(yīng)用作為一個整體注冊一次紧卒,而不是每個組件、模塊都注冊
AppRegistry.registerComponent('MyApp', () => MyApp);
彈性(Flex)寬高 { fleks 收縮 }
在組件樣式中使用 flex 可以使其在可利用的空間中動態(tài)地擴(kuò)張或收縮诗祸。
一般而言我們會使用 flex:1來指定某個組件擴(kuò)張以撐滿所有剩余的空間跑芳。
- 如果有多個并列的子組件使用了flex:1,則這些子組件會平分父容器中剩余的空間直颅。
- 如果這些并列的子組件的 flex 值不一樣博个,則誰的值更大,誰占據(jù)剩余空間的比例就更大(即占據(jù)剩余空間的比等于并列組件間 flex 值的比)功偿。
組件能夠撐滿剩余空間的前提是其父容器的尺寸不為零盆佣。如果父容器既沒有固定的 width 和 height,也沒有設(shè)定flex械荷,則父容器的尺寸為零共耍。其子組件如果使用了flex,也是無法顯示的吨瞎。
import React, { Component } from 'react';
import {
AppRegistry,
View
} from 'react-native';
class MyApp extends Component {
render() {
return (
// 試試去掉父View中的 flex:1 // 如果去掉 子組件不顯示痹兜!
// 則父 View 不在具有尺寸,因此子組件也無法在撐開
// 然后再用 height:300 來替代父View的 flex:1 試試看颤诀?
<View style={{flex: 1}}>
<View style={{flex:1,backgroundColor:'powderblue'}} />
<View style={{flex:2,backgroundColor:'skyblue'}} />
<View style= {{flex:3,backgroundColor:'steelblue'}} />
</View>
);
}
}
AppRegistry.registerComponent('MyApp', () => MyApp);
效果圖: