Reactnative可以調(diào)用原生模塊,原生模塊也可以給JavaScript發(fā)送事件通知.最好的方法是繼承RCTEventEmitter.自定義繼承自PushEventEmitter的子類RCTEventEmitter.
#import <Foundation/Foundation.h>#import <React/RCTBridgeModule.h>#import <React/RCTEventEmitter.h>@interface PushEventEmitter : RCTEventEmitter <RCTBridgeModule>- (void)addEventReminderReceived:(NSNotification *)notification;@end
實(shí)現(xiàn)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 設(shè)置:
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();// 移除通知 }
調(diào)用測(cè)試:
PushEventEmitter *eventEmitter = [PushEventEmitter allocWithZone:nil];
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持VEVB武林網(wǎng)。
|
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注