React Native——特定平台代码

前言

特定平台代码,故名思意,就是针对不同的平台 IOS 和 Android 编写不同的代码。简而言之,就是做兼容。在浏览器环境中一般是 UA 判断之类的。而在移动端开发中,React Native 提供了两个方法来区分平台。(需要注意的是,一些内置的组件也会只在特定平台上有效)

Platform 模块

Platform 模块是 RN 提供的一个检查当前平台的模块,Platform.OS 在 IOS 上为 “ios”,在 Android 上为 “android”。
例如:

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

const styles = StyleSheet.create({
	width: Platform.OS === 'android' ? 300 : 100
})

需要注意的是 Platform 模块还有一个 select 方法,可以根据不同的平台编写不同的样式。
例如:

  1. 针对不同平台设置不同颜色
import { Platform, StyleSheet } from 'react-native'

const styles = StyleSheet.create({
	containter: {
		flex: 1,
		...Platform.select({
			ios: {
				backgroudColor: #fff
			},
			android: {
				backgroundColor: #faa
			}
		})
	}
})
  1. 针对不同平台返回不同组件
import { Platform, StyleSheet } from 'react-native'

// 此时必须是自执行函数
const Component = Platfrom.select({
	ios: () => require("IOSComponent"),
	android: () => require("AndroidComponent")
})()

并且 Platform 模块还可以获取当前 IOS 或 Android 版本。
例如:

import { Platform } from 'react-native'

console.log(Platform.Version)

特定平台扩展名

RN 会在在运行的时候会对文件目录进行判断,会根据文件目录具有的特定扩展名加载平台所对应的文件。
例如:

定义组件目录
Button.ios.js
Button.android.js

代码中引用
import Button from './Button'

PS:这就让我想起 Android 开发中对于不同语言也会根据文件目录加载对于语言的 .xml。

发布了140 篇原创文章 · 获赞 16 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/qq_42049445/article/details/103616994