Dimensions
sunnylqm(100.00%)
本文档贡献者:本模块用于获取设备屏幕的宽高。
useWindowDimensions
is the preferred API for React components. UnlikeDimensions
, 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.
示例
- 函数组件示例
- Class组件示例
文档
方法
get()
static get(dim)
初始的尺寸信息应该在runApplication
之后被执行,这样才可以在任何其他的 require 被执行之前使用。不过在稍后可能还会更新。
示例: const {height, width} = Dimensions.get('window');
参数:
Name | Type | Required | Description |
---|---|---|---|
dim | string | Yes | 想要获取的尺寸信息的字段名。 @returns {Object?} 返回的尺寸信息值。 |
For Android the
window
dimension will exclude the size used by thestatus bar
(if not translucent) andbottom navigation bar
addEventListener()
static addEventListener(type, handler)
Add an event handler. Supported events:
change
: Fires when a property within theDimensions
object changes. The argument to the event handler is an object withwindow
andscreen
properties whose values are the same as the return values ofDimensions.get('window')
andDimensions.get('screen')
, respectively.window
- Size of the visible Application windowscreen
- Size of the device's screen
removeEventListener()
static removeEventListener(type, handler)
Remove an event handler.
set()
static set(dims)
这个函数只应该被原生代码调用。 by sending the didUpdateDimensions event.
参数:
Name | Type | Required | Description |
---|---|---|---|
dims | object | Yes | string-keyed object of dimensions to set |