跳至主内容
版本:0.79

平台模块

非官方测试版翻译

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

示例


参考

属性

constants

tsx
static constants: PlatformConstants;

返回包含所有可用平台通用常量及特定常量的对象。

属性:

Name
TypeOptionalDescription
isTestingbooleanNo
reactNativeVersionobjectNoInformation about React Native version. Keys are major, minor, patch with optional prerelease and values are numbers.
Version
Android
numberNoOS version constant specific to Android.
Release
Android
stringNo
Serial
Android
stringNoHardware serial number of an Android device.
Fingerprint
Android
stringNoA string that uniquely identifies the build.
Model
Android
stringNoThe end-user-visible name for the Android device.
Brand
Android
stringNoThe consumer-visible brand with which the product/hardware will be associated.
Manufacturer
Android
stringNoThe manufacturer of the Android device.
ServerHost
Android
stringYes
uiMode
Android
stringNoPossible values are: 'car', 'desk', 'normal','tv', 'watch' and 'unknown'. Read more about Android ModeType.
forceTouchAvailable
iOS
booleanNoIndicate the availability of 3D Touch on a device.
interfaceIdiom
iOS
stringNoThe interface type for the device. Read more about UIUserInterfaceIdiom.
osVersion
iOS
stringNoOS version constant specific to iOS.
systemName
iOS
stringNoOS name constant specific to iOS.

isPad
iOS

tsx
static isPad: boolean;

返回布尔值,表示设备是否为 iPad。

Type
boolean

isTV

tsx
static isTV: boolean;

返回布尔值,表示设备是否为电视设备。

Type
boolean

isVision

tsx
static isVision: boolean;

返回布尔值,表示设备是否为 Apple Vision 设备。注意:若使用为 iPad 设计的 Apple Vision ProisVision 将返回 falseisPad 返回 true

Type
boolean

isTesting

tsx
static isTesting: boolean;

返回布尔值,表示应用是否在设置了测试标志的开发者模式下运行。

Type
boolean

OS

tsx
static OS: 'android' | 'ios';

返回表示当前操作系统的字符串值。

Type
enum('android', 'ios')

Version

tsx
static Version: 'number' | 'string';

返回当前操作系统的版本号。

Type
number
Android

string
iOS

方法

select()

tsx
static select(config: Record<string, T>): T;

返回最适合当前运行平台的值。

参数:

NameTypeRequiredDescription
configobjectYesSee config description below.

select 方法返回最适合当前运行平台的值。具体规则:在手机设备上优先使用 androidios 键值;若未指定则使用 native 键值,最后回退到 default 键值。

config 参数为包含以下键的对象:

  • android (任意类型)

  • ios (任意类型)

  • native (任意类型)

  • default (任意类型)

使用示例:

tsx
import {Platform, StyleSheet} from 'react-native';

const styles = StyleSheet.create({
container: {
flex: 1,
...Platform.select({
android: {
backgroundColor: 'green',
},
ios: {
backgroundColor: 'red',
},
default: {
// other platforms, web for example
backgroundColor: 'blue',
},
}),
},
});

这将使容器在所有平台具有 flex: 1 属性,在 Android 上显示绿色背景,iOS 上显示红色背景,其他平台显示蓝色背景。

由于平台键值可以是 any 类型,select 方法也可用于返回平台特定组件,如下所示:

tsx
const Component = Platform.select({
ios: () => require('ComponentIOS'),
android: () => require('ComponentAndroid'),
})();

<Component />;
tsx
const Component = Platform.select({
native: () => require('ComponentForNative'),
default: () => require('ComponentForWeb'),
})();

<Component />;