需求:由IOS原生端主动发起调用,传递参数给RN平台。
一、IOS端
1、.h文件
#import <Foundation/Foundation.h>
#import <React/RCTBridgeModule.h>
#import <React/RCTEventEmitter.h>
#import <React/RCTBridge.h>
@interface ReactInteraction : RCTEventEmitter <RCTBridgeModule>
- (void)notifyModeChange:(NSString*) result;
+(id)allocWithZone:(NSZone *)zone ;
@end
2、.m文件
// ReactInteraction.m
// Neurmt
// Created by xzy on 2020/3/30.
// Copyright © 2020 xue. All rights reserved.
//
#import "ReactInteraction.h"
@implementation ReactInteraction
RCT_EXPORT_MODULE();
//.m文件
+(id)allocWithZone:(NSZone *)zone {
static ReactInteraction *sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [super allocWithZone:zone];
});
return sharedInstance;
}
- (NSArray<NSString *> *)supportedEvents
{
return @[@"EventReminder",@"EventWeiXinPayFinish",@"currentMode"];
}
- (void)notifyModeChange:(NSString*) result
{
[self sendEventWithName:@"currentMode" body:@{@"result": result}];
}
@end
3、bridge赋值
rootView = [[RCTRootView alloc]initWithBridge:[MallBridgeAPI shareInstance]
moduleName:@"rmtApp"
initialProperties:props];
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(clickBack) name:@"openHomePage" object:(nil)];
NSLog(@"Neurmt:结束调用Bundle");
}
[ReactInteraction allocWithZone: nil].bridge = rootView.bridge;
4、调用
ReactInteraction * reactInteraction=[[ReactInteraction alloc] init];
[reactInteraction notifyModeChange:@"dark"];
二、RN端
import {
***
NativeModules,
NativeEventEmitter
} from 'react-native';
…
const eventEmitter = new NativeEventEmitter(ReactInteraction);
…
eventEmitter.addListener('currentMode',this.colorModeChange);
}
…
colorModeChange = (result)=> {
if (Platform.OS === 'android') {
…
}else{
…
}
}