React Native 提供了一个模块来检测应用程序运行的平台。您可以使用检测逻辑来实现特定于平台的代码。当组件只有一小部分是特定于平台的时,请使用此选项。
import {Platform, StyleSheet} from 'react-native';
const styles = StyleSheet.create({
height: Platform.OS === 'ios' ? 200 : 100,
});
Platform.OS 在 iOS 上运行时为 ios,在 Android 上运行时为 android。
还有一个 Platform.select 方法可用,给定一个包含 Platform.OS 作为键的对象,返回您当前运行的平台的值。
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 上是蓝色背景色。
由于它接受任何值,因此您还可以使用它来返回特定于平台的组件,如下所示:
const Component = Platform.select({
ios: () => require('ComponentIOS'),
android: () => require('ComponentAndroid'),
})();
<Component />;
检测 Android 版本 在 Android 上,Platform 模块也可用于检测应用运行的 Android 平台的版本:
import {Platform} from 'react-native';
if (Platform.Version === 25) {
console.log('Running on Nougat!');
}
检测 iOS 版本 在 iOS 上,Version 是 -[UIDevice systemVersion] 的结果,它是一个带有当前操作系统版本的字符串。系统版本的一个例子是“10.3”。例如,要检测 iOS 上的主要版本号:
import {Platform} from 'react-native';
const majorVersionIOS = parseInt(Platform.Version, 10);
if (majorVersionIOS <= 9) {
console.log('Work around a change in behavior');
}