Platform区分不同平台

跨平台样式与组件加载
本文详细介绍如何在React Native中使用Platform模块实现跨平台样式设置和组件加载,通过Platform.OS属性区分iOS与Android平台,利用select方法根据不同平台返回特定样式,并介绍如何加载不同平台的组件。

用于区分平台

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值