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];
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VEVB武林網。
新聞熱點
疑難解答