React Native

React Native - 05 - 宽与高

2018-01-31  本文已影响165人  wanqijian

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

固定尺寸

设置组件尺寸的最简单方法是在样式中添加一个固定的宽度和高度。 React Native中的所有维度都是无单位的,并且表示与密度无关的像素。

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: 'powderblue' }} />
                <View style={{ width: 100, height: 100, backgroundColor: 'skyblue' }} />
                <View style={{ width: 150, height: 150, backgroundColor: 'steelblue' }} />
            </View>
        );
    }
}
image.png

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

Flex尺寸

在组件样式中使用flex可以使组件根据可用空间动态扩展和缩小。通常情况下,您将使用flex:1,它告诉组件填充所有可用的空间,并在相同的父组件之间均匀地共享。弯曲度越大,与其兄弟姐妹相比,组件所占空间的比例就越高。

如果组件的父级的尺寸大于0,则组件只能展开以填充可用空间。如果父级没有固定的宽度和高度,或者Flex没有固定宽度,则父级将具有0的尺寸,并且flex子项将不可见。

import React, { Component } from 'react';
import { 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>
      );
    }
}
image.png
上一篇 下一篇

猜你喜欢

热点阅读