Platform区分不同平台

用于区分平台

OS 属性

表示当前的平台类型。只有 iosandroid 两个值。如可以使用为同一个属性在不同的平台上赋不同的值

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

select 方法

根据平台返回不同的值

如下,在 android 平台上 bgcolor 为 blue。但是在两个平台上,flex 的值都是 1。

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

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

利用该特性,可以在不同的平台加载不同的组件:

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

<Component />;

.android 文件

rn 系统会自动识别 .android 与 .ios 文件

系统会根据不同的平台加载不同的后缀名的文件。假设有如下文件:

BigButton.ios.js
BigButton.android.js

使用时可以只写前面的 BigButton,如下:

const BigButton = require('./BigButton');

rn 系统会根据不同的平台加载 .android 或 .ios 文件。


转发链接:https://www.jianshu.com/p/df4845b0e6b9

原文地址:https://www.cnblogs.com/itgezhu/p/11134458.html