原生与RN通信

  • Post author:
  • Post category:其他


RN与原生的通信

此文以iOS与RN通信为例实现了

1.RN给原生发消息:RN调用原生方法,传递参数

原生中导出

MODULE



METHOD

供RN调用

RCT_EXPORT_MODULE(PushNative)

// RN跳转原生界面

RCT_EXPORT_METHOD(RNOpenChatVCWithUserInfo:(NSDictionary *)userInfo){

dispatch_async(dispatch_get_main_queue(), ^{

RootTabBarController *tabBar = [RootTabBarController new];

AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication] delegate];

[app.nav pushViewController:tabBar animated:NO];

});

}

RN中 先导入,再调用

import { …, NativeModules } from ‘react-native’

NativeModules.PushNative.RNOpenChatVCWithUserInfo(UserInfo)

2.原生给RN发消息:原生通讯类发出消息事件,RN中捕捉

原生发出消息事件

PushNative * pushNative = [PushNative shareInstance];

[pushNative sendEventWithName:@”onCloseWithIndex” body:@{@”selIndex”: @0}];

RN中

import {…,NativeModules,NativeEventEmitter} from ‘react-native’

const PushNativeEmitter = new NativeEventEmitter(NativeModules.PushNative);

this.listener = PushNativeEmitter.addListener(‘onCloseWithIndex’, (obj) => { // 处理 }

上面为通信逻辑,具体实现为通信类

#import <Foundation/Foundation.h>
#import <React/RCTBridgeModule.h>
#import <React/RCTEventEmitter.h>
#import <React/RCTBridge.h>
#import <React/RCTEventDispatcher.h>

NS_ASSUME_NONNULL_BEGIN

@interface PushNative : RCTEventEmitter <RCTBridgeModule>

+(instancetype)shareInstance;

@end

NS_ASSUME_NONNULL_END

----------------------上通信类.h   下通信类.m---------------



#import "PushNative.h"
#import "AppDelegate.h"
#import "BaseNav.h"
#import "RootTabBarController.h"

@implementation PushNative

static PushNative* _instance = nil;
+(instancetype)shareInstance
{
  static dispatch_once_t onceToken ;
  dispatch_once(&onceToken, ^{
    _instance = [[super allocWithZone:NULL] init] ;
  }) ;
  return _instance;
}
+ (instancetype)allocWithZone:(struct _NSZone *)zone{
  return [PushNative shareInstance] ;
}

RCT_EXPORT_MODULE(PushNative)

- (NSArray<NSString *> *)supportedEvents
{
  return @[@"onCloseWithIndex"];
}

// RN跳转原生界面
RCT_EXPORT_METHOD(RNOpenChatVCWithUserInfo:(NSDictionary *)userInfo){
  
    dispatch_async(dispatch_get_main_queue(), ^{

      RootTabBarController *tabBar = [RootTabBarController new];
      
      AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication] delegate];
      [app.nav pushViewController:tabBar animated:NO];
    });

  }



版权声明:本文为oop__qoo原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。