#React Native#104混合开发基础篇<1>
(2017-10-27 11:45:29)分类: 计算机相关 |
主要是RN如何做到与原生代码通信的,并且使用原生与RN代码页面的随意切换。主要以调用原生通讯录为实例。
1.IOS混合开发:
1.1RN调用IOS。
为了实现RN与ObjectC
互通消息,在xcode建个RCTBridgeModule 的协议类,新建如下类:
NewFile->IOS->Cocoa Touch Class
-> class: exampleInterface,subclass of
:NSobject->create;
ExampleInterface.h
#import "RCTBridgeModule.h"
#import "RCTBridge.h"
#import "RCTEventDispatcher.h"
@interface
ExampleInterface:NSObject
@property (nonatomic,strong) NSString
* contactName;
@property (nonatomic,strong) NSString
* contactPhoneNum;
@end
ExampleInterface.m
引入RCT_EXPORT_MODULE();
RCT_EXPORT_METHOD(sendMessage:(NSString *)msg){
//解析msg
}
在React-Native 的js页面,添加
var ExampleInterface =
require('react-native').NativeModules.ExampleInterface;
ExampleInterface.sendMessage('"messagType":"pickContact"}');
这样就调用了原生端代码。
1.2 IOS调RN
#import "RCTBridge.h"
#import "RCTEventDispatcher.h"
……
[self.bridge.eventDispacher
sendAppEventWithName:@"NativeModuleMsg"
body:@{@"message":str}];
在RN js代码中:
var {NativeAppEventEmitter} =
require('react-native');
……
this.NativeMsgSubscription =
NativeAppEventEmitter.addListener('NativeModuleMsg',(reminder)
=> {this.handleMessage(reminder.message);});
这样交互的代码可以了。
1.3 RN与原生界面切换。
RCTRootView *rootView = [[RCTRootView
alloc] initWithBundleURL:jsCodeLocation
如果需要最初是原生界面,就直接切换。
1.4 IOS 与RN 传递参数
通常只用一个字符串。如果参数多,就用JSON转字符串来切换。
1.5 RN 当前工作机制会被一个GCD(grand Central
Dispatch)串行分发队列将开发者代码分发到任意线程中,如果必须用主线程调用,就用dispatch_get_main_queue();,
如果需要长时间处理就用RCTAsyncLocalStorage
模块来创建自己队列,dispatch_queue_create("com.facebook,React.AsycLocalStorageQueue",DISPATCH_QUEUE_SERIAL);
如果想用异步线程处理,就用dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0),^
{耗时操作});
1.6 RN 实现Promise
RCT_REMAP_METHOD(getCurrentInfo,
resolver:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject) {
@try
{
NSString *
version = [[NSBundle
mainBundle]
objectForInfoDictionaryKey: @ "CFBundleShortVersionString" ];
NSString *
build = [[NSBundle
mainBundle]
objectForInfoDictionaryKey: ( NSString
*)kCFBundleVersionKey];
resolve(@{@ "versionName":
version, @"versionCode":
build}); } @catch
(NSException
*exception)
{
NSError *error
= [NSError
errorWithDomain:RNUPGRADE_ERROR_DOMAIN
code:1
userInfo:
exception.userInfo];
reject(exception .name,
exception.reason,
error); } }
在JS端就是
var
ExampleInterface =
require("react-native").NativeModules.ExampleInterface;
ExampleInterface.getCurrentInfo.then((result)=>{处理成功回调}).catch((result)=>{失败回调});