本文主要是介绍统一ANDROID与IOS两个平台的程序入口区分平台的组件简介,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
统一ANDROID与IOS两个平台的程序入口&&区分平台的组件简介
本站文章均为 李华明Himi 原创,转载务必在明显处注明:
转载自【黑米GameDev街区】 原文链接:
http://www.himigame.com/react-native/2260.html
本篇介绍两个细节:
1. 关于如何将index.Android.js 与index.iOS.js统一管理起来。
2. Platform 组件的简单介绍与使用
一:将index.android.js 与index.ios.js统一管理起来。
由于React本身就是跨平台的,但是创建的React项目总会有各自不同的程序入口文件,如下图展示目录结构:

标识1:这里是两个平台的项目文件夹,这里一般就是针对各平台不同配置、嵌入第三方插件等专属平台相关设置与添加的地方。
标识2: React 在不同平台调用的不同入口文件。
那么正常情况下,我们只要不涉及到某个平台独有的特性代码、组件或插件等,我们就完全没有必要走两个不同的入口。否则在Android上运行可能index.ios下运行的代码段还要拷贝到index.android里,反之亦然。
因此我们可以新建一个组件class 让俩平台共同显示这个class,就可以避免这种来回拷贝浪费的时间。
1. 假设我们新建了一个叫Main.js的组件Class
2. 然后index.ios.js如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | import React , { AppRegistry , Component , View , } from 'react-native' ; import Main from './Main' ; class AwesomeProject extends Component { render ( ) { return ( < Main / > ) ; } } AppRegistry . registerComponent ( 'AwesomeProject' , ( ) = > AwesomeProject ) ; |
3.index.android.js如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | import React , { AppRegistry , Component , View , } from 'react-native' ; import Main from './Main' ; class AwesomeProject extends Component { render ( ) { return ( < Main / > ) ; } } AppRegistry . registerComponent ( 'AwesomeProject' , ( ) = > AwesomeProject ) ; |
这样统一显示Main组件的内容,以后不论在android还是ios平台都可以完美兼容,小细节,估计大家一看就懂。
二. Platform 组件的简单介绍与使用
有时候我们会区分平台做一些处理,比如充值、适配问题、接入第三方SDK或与原生平台组件进行交互等等。
这时我们就需要 RN提供的 Platform 组件~ 使用很简单,就不多赘述了。
示例:
代码段1:(导入Platform组件)
| import React , { . . . Platform , . . . } from 'react-native' ; |
代码段2:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | testAlert ( ) { if ( Platform . OS === 'ios' ) { Alert . alert ( '测试当前平台' , 'iOS平台' ) ; } else if ( Platform . OS === 'android' ) { Alert . alert ( '测试当前平台' , 'Android平台' ) ; } } render ( ) { return ( < View style = { styles . himiViewStyle } > < Text style = { styles . himiTextStyle } > Himi React Native 教程 < / Text > < View style = { styles . himiViewStyle } > < TouchableHighlight underlayColor = '#f00' onPress = { this . testAlert . bind ( this ) } > < Text style = { { fontSize : 20 } } >点击查看当前平台 < / Text > < / TouchableHighlight > < / View > < / View > ) } |
主要看 testAlert 的函数中的内容,通过Platform.OS获取当前平台类型与android/ios做比较即可得知。
运行效果如下(点击查看动态图):

这篇关于统一ANDROID与IOS两个平台的程序入口区分平台的组件简介的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!