跳到主要内容
新架构实战课 实操 + 基建 + 原理全维度包揽,抢先掌握 React Native 新架构精髓 立即查看 >Version: 0.64

Dimensions

本模块用于获取设备屏幕的宽高。

useWindowDimensions is the preferred API for React components. Unlike Dimensions, it updates as the window's dimensions update. This works nicely with the React paradigm.

import { Dimensions } from 'react-native';

你可以用下面的方法来获取设备的宽高:

const windowWidth = Dimensions.get('window').width;
const windowHeight = Dimensions.get('window').height;

注意:尽管尺寸信息立即就可用,但它可能会在将来被修改(譬如设备的方向改变),所以基于这些常量的渲染逻辑和样式应当每次 render 之后都调用此函数,而不是将对应的值保存下来。(举例来说,你可能需要使用内联的样式而不是在StyleSheet中保存相应的尺寸)。

If you are targeting foldable devices or devices which can change the screen size or app window size, you can use the event listener available in the Dimensions module as shown in the below example.

示例


文档

方法

get()

static get(dim)

初始的尺寸信息应该在runApplication之后被执行,这样才可以在任何其他的 require 被执行之前使用。不过在稍后可能还会更新。

示例: const {height, width} = Dimensions.get('window');

参数:

名称类型Required说明
dimstringYes想要获取的尺寸信息的字段名。 @returns {Object?} 返回的尺寸信息值。

For Android the window dimension will exclude the size used by the status bar (if not translucent) and bottom navigation bar


addEventListener()

static addEventListener(type, handler)

Add an event handler. Supported events:

  • change: Fires when a property within the Dimensions object changes. The argument to the event handler is an object with window and screen properties whose values are the same as the return values of Dimensions.get('window') and Dimensions.get('screen'), respectively.
    • window - Size of the visible Application window
    • screen - Size of the device's screen

removeEventListener()

static removeEventListener(type, handler)

Remove an event handler.


set()

static set(dims)

这个函数只应该被原生代码调用。 by sending the didUpdateDimensions event.

参数:

名称类型Required说明
dimsobjectYesstring-keyed object of dimensions to set