美文网首页iOS开发记录IOS
Reactnative-iOS回调Javascript

Reactnative-iOS回调Javascript

作者: FlyElephant | 来源:发表于2018-08-23 16:57 被阅读22次

    Reactnative可以调用原生模块,原生模块也可以给JavaScript发送事件通知.最好的方法是继承RCTEventEmitter.自定义继承自PushEventEmitter的子类RCTEventEmitter.

    #import <Foundation/Foundation.h>
    #import <React/RCTBridgeModule.h>
    #import <React/RCTEventEmitter.h>
    
    @interface PushEventEmitter : RCTEventEmitter <RCTBridgeModule>
    
    - (void)addEventReminderReceived:(NSNotification *)notification;
    
    @end
    

    实现supportedEvents方法

    #import "PushEventEmitter.h"
    
    @implementation PushEventEmitter
    
    + (id)allocWithZone:(NSZone *)zone {
        static PushEventEmitter *sharedInstance = nil;
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            sharedInstance = [super allocWithZone:zone];
        });
        return sharedInstance;
    }
    
    RCT_EXPORT_MODULE();
    
    - (NSArray<NSString *> *)supportedEvents
    {
        return @[@"EventReminder"];
    }
    
    - (void)addEventReminderReceived:(NSNotification *)notification {
        [self sendEventWithName:@"EventReminder" body:@{@"name": @"FlyElephant"}];
    }
    
    @end
    

    React native 设置:

    import {
        NativeModules,
        NativeEventEmitter,
    } from 'react-native';
    
    const PushEventEmitter  = NativeModules.PushEventEmitter;
    
    const emitterManager = new NativeEventEmitter(PushEventEmitter);
    

    订阅通知和移除通知:

        componentDidMount() {
            subscription = emitterManager.addListener(
                'EventReminder',
                (reminder) => console.log('JavaScript接收到通知:'+reminder.name)
            );
    
        }
        componentWillUnmount(){
            subscription.remove();// 移除通知
        }
    

    调用测试:

        PushEventEmitter *eventEmitter = [PushEventEmitter allocWithZone:nil];
        [eventEmitter addEventReminderReceived:nil];
    

    相关文章

      网友评论

        本文标题:Reactnative-iOS回调Javascript

        本文链接:https://www.haomeiwen.com/subject/pamjmxtx.html