基础篇_高度与宽度

2017-05-18  本文已影响16人  蓝白自由

组件的高度和宽度决定了其在屏幕上显示的尺寸。

指定宽高

最简单的给组件设定尺寸的方式就是在样式中指定固定的 width 和 height。
React Native中的尺寸都是无单位的,表示的是与设备像素密度无关的逻辑像素点。

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>
               );
    }
    
}

// 注册应用(registerComponent)后才能正确渲染
// 注意:只把应用作为一个整体注册一次,而不是每个组件、模块都注册
AppRegistry.registerComponent('MyApp', () => MyApp);

弹性(Flex)宽高 { fleks 收缩 }

在组件样式中使用 flex 可以使其在可利用的空间中动态地扩张或收缩。
一般而言我们会使用 flex:1来指定某个组件扩张以撑满所有剩余的空间。

组件能够撑满剩余空间的前提是其父容器的尺寸不为零。如果父容器既没有固定的 width 和 height,也没有设定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);

效果图:

上一篇 下一篇

猜你喜欢

热点阅读