首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

Height and Width

组件的高度和宽度决定了它在屏幕上的大小。

固定尺寸

设置组件尺寸的最简单方法是将固定样式widthheight样式相加。React Native中的所有维度都是无单位的,并且表示与密度无关的像素。

代码语言:javascript
复制
import React, { Component } from 'react';
import { AppRegistry, View } from 'react-native';

export default class FixedDimensionsBasics 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>
    );
  }
}

// skip this line if using Create React Native App
AppRegistry.registerComponent('AwesomeProject', () => FixedDimensionsBasics);

无论屏幕尺寸如何,以这种方式设置尺寸对于应该始终呈现完全相同尺寸的组件而言都很常见。

Flex尺寸

使用flex的组件的样式有分量膨胀和收缩动态地根据可用空间。通常情况下,您将使用flex: 1它来告诉组件填充所有可用空间,并在相同的父组件之间均匀地共享。flex给定量越大,组件与其兄弟姐妹相比所占空间的比例就越高。

如果组件的父级的维度大于0,则该组件只能展开以填充可用空间。如果父级没有固定的widthheight或者flex,则父级的维度将为0,并且flex子级将不可见。

代码语言:javascript
复制
import React, { Component } from 'react';
import { AppRegistry, View } from 'react-native';

export default class FlexDimensionsBasics extends Component {
  render() {
    return (
      // Try removing the `flex: 1` on the parent View.
      // The parent will not have dimensions, so the children can't expand.
      // What if you add `height: 300` instead of `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>
    );
  }
}

// skip this line if using Create React Native App
AppRegistry.registerComponent('AwesomeProject', () => FlexDimensionsBasics);

在您可以控制组件的大小后,下一步就是学习如何将其布置在屏幕上。

扫码关注腾讯云开发者

领取腾讯云代金券