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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM