Reactnative-i OSフィードバックJavascript

1794 ワード

Reactnativeは原生モジュールを呼び出すことができます.オリジナルモジュールはJavaScriptにイベント通知を送信することもできます.一番いい方法はRCTEvent Emitterを継承します.Push Event Emitterからサブクラスをカスタマイズして継承します.
#import 
#import 
#import 

@interface PushEventEmitter : RCTEventEmitter 

- (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 *)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];