跳至主内容
版本:0.81

尺寸

非官方测试版翻译

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

对于 React 组件,useWindowDimensions 是更推荐的 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 尺寸将排除status bar(非透明时)和bottom navigation bar占用的空间


类型定义

DimensionsValue

属性:

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

ScaledSize

Type
object

属性:

NameType
widthnumber
heightnumber
scalenumber
fontScalenumber