1、指定宽高
styles样式中指定固定的width和height。
React Native 中的尺寸都是无单位的,表示的是与设备像素密度无关的逻辑像素点。
import React from 'react';
import { View } from 'react-native';
const FixedDimensionsBasics = () => {
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>
);
};
export default FixedDimensionsBasics;
2、弹性(Flex)宽高
使用flex:1来指定某个组件扩张以撑满所有剩余的空间。如果有多个并列的子组件使用了flex:1,则这些子组件会平分父容器中剩余的空间。如果这些并列的子组件的flex值不一样,则谁的值更大,谁占据剩余空间的比例就更大。
如果父容器既没有固定的width和height,也没有设定flex,则父容器的尺寸为零。其子组件如果使用了flex,也是无法显示的。
import React from 'react';
import { View } from 'react-native';
const FlexDimensionsBasics = () => {
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>
);
};
export default FlexDimensionsBasics;
3、百分比宽高
按比例填充屏幕上某一部分,又不想使用 flex 布局,可以在组件的style中使用百分比。与弹性宽高相似,百分比宽高要求父容器有一个明确的尺寸。
import React from 'react';
import { View } from 'react-native';
const PercentageDimensionsBasics = () => {
// 如果删除父视图上的“高度:100%”。父对象将没有尺寸标注,因此子对象无法展开。
return (
<View style={{ height: '100%' }}>
<View style={{
height: '15%', backgroundColor: 'powderblue'
}} />
<View style={{
width: '66%', height: '35%', backgroundColor: 'skyblue'
}} />
<View style={{
width: '33%', height: '50%', backgroundColor: 'steelblue'
}} />
</View>
);
};
export default PercentageDimensionsBasics;