react-native: ios原生调用js方法

ReactEventEmit.h

#import

#import

@interface ReactEventEmit : RCTEventEmitter

-(void)goToCashier:(NSString*) result;

@end


ReactEventEmit.m

#import "ReactEventEmit.h"

@implementation ReactEventEmit

@synthesize bridge = _bridge;

RCT_EXPORT_MODULE(ReactEventEmit);

+ (id)allocWithZone:(NSZone*)zone {

    staticReactEventEmit*sharedInstance =nil;

    staticdispatch_once_tonceToken;

    dispatch_once(&onceToken, ^{

        sharedInstance = [superallocWithZone:zone];

    });

    returnsharedInstance;

}

-(NSArray *)supportedEvents{

    return @[@"goToCashier"];

}

-(void)goToCashier:(NSString*) result

{

    NSLog(@"======== cashierSuccess ========== %@",result);

    [self sendEventWithName:@"goToCashier" body:@{@"result": result}];

}

@end

RN的module初始化是由RN内部实现的,所以我们调用这个实例的时候,必须是这样子:

ReactEventEmit *emit = [ReactEventEmit allocWithZone:nil];

 [emit goToCashier:@"fail"];


JS端调用:

const ReactEventEmit = NativeModules.ReactEventEmit;

const myReactEventEmit = new NativeEventEmitter(ReactEventEmit);

this.listener = myReactEventEmit.addListener('goToCashier', (data: { result: string }) => {

        console.warn('====== cashierSuccess ======= ' + JSON.stringify(data));

        this.process(data.result);

      });

你可能感兴趣的:(react-native: ios原生调用js方法)