RN与原生的交互

—-现在还不太懂这个,先码在这里—-
在写RN时不免会遇到与原生交互,下面我分JS调用原生、原生调用JS来讲

JS调用原生

在调用原生时,我们需要实现RCTBridgeModule和RCT_EXPORT_MODULE();
RCT_EXPORT_MODULE();则是一个宏定义,返回moduleName,并且调用+ load方法注册

#define RCT_EXPORT_MODULE(js_name) \
RCT_EXTERN void RCTRegisterModule(Class); \
+ (NSString *)moduleName { return @#js_name; } \
+ (void)load { RCTRegisterModule(self); }

例如我们增加一个bridge方法,获取版本号,getVersion为方法名,callback是原生回调给JS的内容

RCT_EXPORT_METHOD(getVersion : (RCTResponseSenderBlock)callback) {
   NSString *version =
   [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
   callback(@[[NSNull null], @[version]]);
}

然后返回方法的队列为主队列

- (dispatch_queue_t)methodQueue {
   return dispatch_get_main_queue();
}

在JS文件里,我们可以定义一个全局变量

var ZanIntentModule = NativeModules.ZanIntentModule;

然后在使用的时候调用我们在原生时定义方法

ZanIntentModule.getVersion(
(callback) => {
   // do some thing
})

原生调用JS
新版本的调用方式为

ZanEventEmitter *emitter = [[ZanEventEmitter alloc] init];
emitter.bridge = self.bridge;
[emitter sendEventWithName:kGiftReloadData body:nil];

然后在实现RCTBridgeDelegate

- (NSURL *)sourceURLForBridge:(RCTBridge *)bridge {
   return [[NSBundle mainBundle] URLForResource:@"bundle/index.ios" withExtension:@"jsbundle"];
//   return [NSURL URLWithString:@"http://172.17.9.94:8081/index.ios.bundle?platform=ios"];
}

在对应的组件里,需要在componentWillMount增加监听

componentWillMount() {
  this.eventEmitter = NativeAppEventEmitter.addListener(
   'GiftReloadData',
   () => this._reloadData()
 );
}

对应的也需要移除掉监听

componentWillUnmount() {
  subscription.remove();
}

然后原生发送action之后,会触发我们设定好的reloadData()方法

原文链接:https://www.jianshu.com/p/ea61a014ce4e

猜你喜欢

转载自blog.csdn.net/snow51/article/details/80593044
RN
今日推荐