ReactNative: 使用尺寸类Dimensions获取屏幕尺寸

一、简介

在前面创建使用组件时,虽然使用的都是伸缩盒子布局,但是很少使用宽高来进行绝对定位。在iOS中可以通过UIScreen控件获取当前屏幕的宽高,同样地,在RN中提供了一个尺寸组件Dimensions,英文译为“英尺”,开发者通过它也能拿到当前屏幕的宽和高。Dimensions组件类中,声明的函数属性都是静态的,直接通过类名调用即可。

//设置尺寸
static set(dims: {[key:string]: any}): void {}

//获取尺寸
static get(dim: string): Object {}

//添加监听
static addEventListener {}

//移除监听
static removeEventListener {}

  

二、使用

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';

import {
    AppRegistry,
    StyleSheet,
    View,
    Dimensions
} from 'react-native';

//计算屏幕的宽高
let {width, height} = Dimensions.get('window');

export default class ReactNativeDemo extends Component {

    constructor(props){
        super(props);
        this.printWindowWidth();
        this.printWindowHeight();
    }


    //打印屏幕的高度
    printWindowWidth(){
        console.log("iphone8 window width is "+ width);
    }

    //打印屏幕的宽度
    printWindowHeight(){
        console.log("iphone8 window height is "+ height);
    }

    render() {
        return (
            <View style={styles.flex} />
        );
    }
}

const styles = StyleSheet.create({
    flex: {
        flex: 1
    }
});

AppRegistry.registerComponent('ReactNativeDemo', () => ReactNativeDemo);

当前iphone8的尺寸打印如下:

2019-12-14 16:01:38.823 [info][tid:com.facebook.react.JavaScript] Running application "ReactNativeDemo" with appParams: {"rootTag":1,"initialProps":{}}. __DEV__ === true, development-level warning are ON, performance optimizations are OFF

2019-12-14 16:01:38.849 [info][tid:com.facebook.react.JavaScript] iphone8 window width is 375
2019-12-14 16:01:38.851 [info][tid:com.facebook.react.JavaScript] iphone8 window height is 667

 

posted @ 2019-12-14 16:03  XYQ全哥  阅读(1985)  评论(0编辑  收藏  举报