最近一直在學(xué)習(xí)前端的內(nèi)容谅将,這里總結(jié)一下js在不同載體的情況下與原生的交互。
react-Native調(diào)用原生
原生需要導(dǎo)入#import <React/RCTBridgeModule.h>框架重慢,并且遵守RCTBridgeModule協(xié)議
在實(shí)現(xiàn)里面導(dǎo)出模塊(不添加參數(shù)即默認(rèn)為這個(gè)類名)
RCT_EXPORT_MODULE();
然后需要導(dǎo)出方法
// 導(dǎo)出方法饥臂,橋接到j(luò)s的方法返回值類型必須是void
RCT_EXPORT_METHOD(doSomething:(NSString *)testStr) {
NSLog(@"%@ ===> doSomething",testStr);
}
帶有回調(diào)的方法這么處理
/* 回調(diào)參數(shù)至少為兩個(gè),第一個(gè)為狀態(tài)似踱,第二個(gè)為參數(shù) */
RCT_EXPORT_METHOD( doSomething1:(NSString *)testStr callBack:(RCTResponseSenderBlock)callback ){
NSLog(@"%@ ===> doSomething",testStr);
NSString *str1 = @"Callback數(shù)據(jù)"; //準(zhǔn)備回調(diào)回去的數(shù)據(jù)
NSString *str2 = @"Callback數(shù)據(jù)222";
callback(@[[NSNull null],str1,str2]);
}
在react-native這么調(diào)用方法
//NativeAndRNBridge為原生定義的導(dǎo)出模塊
var NativeTest = require('react-native').NativeModules.NativeAndRNBridge;
NativeTest.doSomething1(('RN->原生的數(shù)據(jù)'),(error,str1,str2) => {
if (!error) {
alert(str1+"========"+str2)//返回的數(shù)據(jù)
} else {
console.warn(error);
}
});
Native調(diào)用UIWebView
UIWebView與Native交互時(shí)需要獲取JSContext隅熙,JSContext是JavaScriptCore里面的一個(gè)類
首先你需要定義一個(gè)屬性
@property(nonatomic,strong)JSContext *context;
在網(wǎng)頁(yè)加載完成的這個(gè)代理方法里面通過KVC獲取context
- (void)webViewDidFinishLoad:(UIWebView *)webView{
[self hidenChrysanthemum];
self.context = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
//設(shè)置異常處理
self.context.exceptionHandler = ^(JSContext *context, JSValue *exceptionValue) {
context.exception = exceptionValue;
};
self.context[@"HrefLinkTaobao"] = ^(NSString * url){
dispatch_async(dispatch_get_main_queue(), ^{
//dosomething
});
};
self.context[@"HrefLinkLocal"] = ^(NSString * url){
dispatch_async(dispatch_get_main_queue(), ^{
//dosomething
});
};
self.context[@"native"] = self;
}
這里有一些注意點(diǎn):
1、這里是有循環(huán)應(yīng)用的問題屯援,如果在方法的block中執(zhí)行一些代碼猛们,用到了self需要對(duì)self進(jìn)行weak操作一下。
2狞洋、線程的問題弯淘,調(diào)用web的方法都是異步線程去調(diào)取的,所以回到原生的里面吉懊,做一些操作(非耗時(shí))的時(shí)候最好是轉(zhuǎn)到主線程里面來