Skip to main content

Dimensions

useWindowDimensions 是 React 组件的首选 API。与 Dimensions 不同,它随着窗口尺寸的更新而更新。这与 React 范例配合得很好。

¥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';

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

¥You can get the application window's width and height using the following code:

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

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

¥Although dimensions are available immediately, they may change (e.g due to device rotation, foldable devices etc) so any rendering logic or styles that depend on these constants should try to call this function on every render, rather than caching the value (for example, using inline styles rather than setting a value in a StyleSheet).

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

¥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.

示例

¥Example

参考

¥Reference

方法

¥Methods

addEventListener()

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

添加事件处理程序。支持的事件:

¥Add an event handler. Supported events:

  • change:当 Dimensions 对象中的属性更改时触发。事件处理程序的参数是 DimensionsValue 类型对象。

    ¥change: Fires when a property within the Dimensions object changes. The argument to the event handler is a DimensionsValue type object.


get()

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

初始尺寸在调用 runApplication 之前设置,因此它们应该在运行任何其他需求之前可用,但可能会在以后更新。

¥Initial dimensions are set before runApplication is called so they should be available before any other require's are run, but may be updated later.

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

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

参数:

¥Parameters:

名称类型描述
暗淡
必填
string调用 set 时定义的维度名称。返回维度的值。

对于 Android,window 尺寸将排除 status bar(如果不是半透明)和 bottom navigation bar 使用的尺寸

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


类型定义

¥Type Definitions

DimensionsValue

属性:

¥Properties:

名称类型描述
windowScaledSize可见应用窗口的大小。
screenScaledSize设备屏幕的尺寸。

ScaledSize

类型
object

属性:

¥Properties:

名称类型
widthnumber
heightnumber
scalenumber
fontScalenumber