跳至主内容
版本:当前版本

尺寸

非官方测试版翻译

本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →

信息

useWindowDimensions 是 React 组件的推荐 API。与 Dimensions 不同,它会在窗口尺寸更新时自动更新。这非常契合 React 的编程范式。

tsx
import {Dimensions} from 'react-native';

可通过以下代码获取应用窗口的宽度和高度:

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

尽管尺寸数据可以立即获取,但它们可能会发生变化(例如设备旋转、折叠屏设备等)。因此,任何依赖于这些常量的渲染逻辑或样式都应在每次渲染时调用此函数,而不是缓存其值(例如,使用内联样式而非在 StyleSheet 中设定固定值)。

如果目标设备是折叠屏或屏幕尺寸/应用窗口尺寸可变的设备,可以使用 Dimensions 模块提供的事件监听器,如下例所示。

示例

参考

方法

addEventListener()

tsx
static addEventListener(
type: 'change',
handler: ({
window,
screen,
}: DimensionsValue) => void,
): EmitterSubscription;

添加事件处理器。支持的事件类型:

  • change:当 Dimensions 对象中的属性变化时触发。事件处理函数的参数是 DimensionsValue 类型的对象。

get()

tsx
static get(dim: 'window' | 'screen'): ScaledSize;

初始尺寸在调用 runApplication 前已设置,因此在其他 require 执行前即可获取,但后续可能更新。

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

参数:

NameTypeDescription
dim
Required
stringName of dimension as defined when calling set. Returns value for the dimension.
备注

在 Android 上,window 的尺寸会减去状态栏(如果非透明)和底部导航栏的高度。

类型定义

DimensionsValue

属性:

NameTypeDescription
windowScaledSizeSize of the visible Application window.
screenScaledSizeSize of the device's screen.

ScaledSize

Type
object

属性:

NameType
widthnumber
heightnumber
scalenumber
fontScalenumber