Platform
示例
参考
属性
constants
tsx
static constants: PlatformConstants;
返回一个包含与平台相关的、所有可用的通用和特定常量的对象。
属性
姓名 | 类型 | 可选 | 描述 |
|---|---|---|---|
| isTesting | 布尔值 | 否 | |
| reactNativeVersion | 对象 | 否 | 关于 React Native 版本的信息。键包括 major、minor、patch,可选的有 prerelease,值都是 number。 |
| 版本 Android | 数字 | 否 | 特定于 Android 的操作系统版本常量。 |
| Release Android | 字符串 | 否 | |
| Serial Android | 字符串 | 否 | Android 设备的硬件序列号。 |
| Fingerprint Android | 字符串 | 否 | 唯一标识构建的字符串。 |
| Model Android | 字符串 | 否 | Android 设备的面向最终用户的名称。 |
| Brand Android | 字符串 | 否 | 产品/硬件将关联的面向消费者的品牌。 |
| Manufacturer Android | 字符串 | 否 | Android 设备的制造商。 |
| ServerHost Android | 字符串 | 是 | |
| uiMode Android | 字符串 | 否 | 可能的值包括:'car'、'desk'、'normal'、'tv'、'watch' 和 'unknown'。阅读更多关于 Android ModeType 的信息。 |
| forceTouchAvailable iOS | 布尔值 | 否 | 指示设备上 3D Touch 的可用性。 |
| interfaceIdiom iOS | 字符串 | 否 | 设备的界面类型。阅读更多关于 UIUserInterfaceIdiom 的信息。 |
| osVersion iOS | 字符串 | 否 | 特定于 iOS 的操作系统版本常量。 |
| systemName iOS | 字符串 | 否 | 特定于 iOS 的操作系统名称常量。 |
isPad iOS
tsx
static isPad: boolean;
返回一个布尔值,表示设备是否为 iPad。
| 类型 |
|---|
| 布尔值 |
isTV
tsx
static isTV: boolean;
返回一个布尔值,表示设备是否为电视。
| 类型 |
|---|
| 布尔值 |
isVision
tsx
static isVision: boolean;
返回一个布尔值,表示设备是否为 Apple Vision。如果您使用的是 Apple Vision Pro (为 iPad 设计),isVision 将为 false,但 isPad 将为 true。
| 类型 |
|---|
| 布尔值 |
isTesting
tsx
static isTesting: boolean;
返回一个布尔值,表示应用程序是否在设置了测试标志的开发者模式下运行。
| 类型 |
|---|
| 布尔值 |
OS
tsx
static OS: 'android' | 'ios';
返回表示当前操作系统的字符串值。
| 类型 |
|---|
enum('android', 'ios') |
Version
tsx
static Version: 'number' | 'string';
返回操作系统的版本。
| 类型 |
|---|
| 数字 Android 字符串 iOS |
方法
select()
tsx
static select(config: Record<string, T>): T;
返回当前运行平台上最匹配的值。
参数:
| 姓名 | 类型 | 必需 | 描述 |
|---|---|---|---|
| config | 对象 | 是 | 请参阅下面的配置说明。 |
Select 方法返回当前运行平台上最匹配的值。也就是说,如果你在手机上运行,android 和 ios 键将优先。如果未指定这些键,将使用 native 键,然后是 default 键。
config 参数是一个对象,包含以下键:
android(any)ios(any)native(any)default(any)
用法示例
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 />;