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];
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。
如对本文有疑问, 点击进行留言回复!!
IOS系统中使用new Date()报错valid Date
解决Android10读取不到/sdcard/、/storage/emulated/0/文件的问题
Codeforces Round #649 (Div. 2)-B. Most socially-distanced subsequence(思维)
网友评论