您好,登錄后才能下訂單哦!
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];
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。