首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

Platform Specific Code

在构建跨平台应用程序时,您需要尽可能多地使用代码。如果代码有所不同,可能会出现场景,例如,您可能希望为iOS和Android实现单独的可视化组件。

React Native提供了两种轻松组织代码并将其按平台分开的方法:

  • 使用Platform模块。
  • 使用平台特定的文件扩展名。

某些组件可能具有只能在一个平台上运行的属性。所有这些道具都附有注释,@platform并在网站旁边有一个小徽章。

平台模块

React Native提供了一个模块,用于检测应用程序运行的平台。您可以使用检测逻辑来实现特定于平台的代码。只有组件的小部分是平台特定的时才使用此选项。

代码语言:javascript
复制
import { Platform, StyleSheet } from 'react-native';

const styles = StyleSheet.create({
  height: (Platform.OS === 'ios') ? 200 : 100,
});

Platform.OSios在iOS上android运行并在Android上运行时使用。

还有Platform.select一种可用的方法,给定一个包含Platform.OS作为键的对象,返回当前运行的平台的值。

代码语言:javascript
复制
import { Platform, StyleSheet } from 'react-native';

const styles = StyleSheet.create({
  container: {
    flex: 1,
    ...Platform.select({
      ios: {
        backgroundColor: 'red',
      },
      android: {
        backgroundColor: 'blue',
      },
    }),
  },
});

这将导致容器flex: 1在两个平台上都具有iOS上的红色背景色和Android上的蓝色背景色。

由于它接受any价值,您也可以使用它来返回特定于平台的组件,如下所示:

代码语言:javascript
复制
const Component = Platform.select({
  ios: () => require('ComponentIOS'),
  android: () => require('ComponentAndroid'),
})();

<Component />;

检测Android版本

在Android上,该Platform模块还可用于检测应用程序运行的Android平台的版本:

代码语言:javascript
复制
import { Platform } from 'react-native';

if (Platform.Version === 25) {
  console.log('Running on Nougat!');
}

检测iOS版本

在iOS Version-[UIDevice systemVersion],这是与当前版本的操作系统相关的字符串的结果。系统版本的一个例子是“10.3”。例如,要检测iOS上的主要版本号:

代码语言:javascript
复制
import { Platform } from 'react-native';

const majorVersionIOS = parseInt(Platform.Version, 10);
if (majorVersionIOS <= 9) {
  console.log('Work around a change in behavior'); 
}

平台特定的扩展

当您的平台特定的代码更复杂时,您应该考虑将代码拆分为单独的文件。反应本地文件时有一个将检测.ios..android.扩展,从其他组件时,需要加载平台相关文件。

例如,假设你的项目中有以下文件:

代码语言:javascript
复制
BigButton.ios.js
BigButton.android.js

然后您可以按如下方式要求组件:

代码语言:javascript
复制
const BigButton = require('./BigButton');

React Native会根据运行平台自动选择正确的文件。

扫码关注腾讯云开发者

领取腾讯云代金券