zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    2019 学霸君java面试笔试题 (含面试题解析)
    2019 大众书网Java面试笔试题 (含面试题解析)
    2019 中细软java面试笔试题 (含面试题解析)
    2019 企叮咚java面试笔试题 (含面试题解析)
    js 去掉数组对象中的重复对象
    canvas霓虹雨
    nvm的安装
    socket.io 中文文档
    Nginx(三)------nginx 反向代理
    github入门到上传本地项目
  • 原文地址:https://www.cnblogs.com/XYQ-208910/p/12039923.html
Copyright © 2011-2022 走看看