构建一个跨平台app时,你会想尽可能多地去复用代码。不过有时候你会需要针对特定的平台使用不同的代码,比如,你可能会想给iOS和Android两个平台使用不同的视觉组件。
React Native提供了两种方式让你可以轻松地按平台来组织和分离你的代码:
- 使用Platform模块;
- 使用针对特定平台的文件扩展名。
目录
Platform模块:
React Native提供了一个Platform模块用于检测当前运行app的平台。你可以根据这个检测逻辑去应用对应的针对特定平台的代码。如果一个组件中只有一小部分代码是针对特定平台的,可以使用这种方式。
import { Platform, StyleSheet } from 'react-native'; const styles = StyleSheet.create({ height: (Platform.OS === 'ios') ? 200 : 100, });
在上面的代码里,Platform.OS的值在iOS平台上会是ios,在Android平台上会是android。
另外,Platform模块还提供了一个Platform.select方法,该方法接受一个对象入参,该入参对象的key是Platform.OS的枚举值(ios、android),Platform.select方法会返回当前所在平台对应的key对应的value(有点绕口-_-)。
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平台中显示的背景色为蓝色。
Platform.select方法的key(ios、android)对应的value可以是任意的value,所以你也可以通过这种方式返回针对特定平台的组件,就像下面这样:
const Component = Platform.select({ ios: () => require('ComponentIOS'), android: () => require('ComponentAndroid'), })(); <Component />;
针对特定平台的文件扩展名:
如果你针对特定平台的代码比较复杂的话,你应该考虑将它们拆分到独立的文件中。当一个组件要加载的另外一个组件对应的文件名有.ios.和/或.android.扩展名时,React Native会根据当前所处平台来加载对应的文件。
比如说,如果你的项目中有以下两个文件:
BigButton.ios.js BigButton.android.js
然后你可以用下面这种方式去引入组件:
const BigButton = require('./BigButton');
这样子,React Native就会根据当前运行app的平台来自动加载对应的文件了。
参考:
- https://facebook.github.io/react-native/docs/platform-specific-code.html