Reactnative可以调用原生模块,原生模块也可以给JavaScript发送事件通知.最好的方法是继承RCTEventEmitter.自定义继承自PushEventEmitter的子类RCTEventEmitter.
复制代码
1
2
3
4
5
6
7
8
9#import <Foundation/Foundation.h> #import <React/RCTBridgeModule.h> #import <React/RCTEventEmitter.h> @interface PushEventEmitter : RCTEventEmitter <RCTBridgeModule> - (void)addEventReminderReceived:(NSNotification *)notification; @end
实现supportedEvents方法
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25#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 设置:
复制代码
1
2
3
4
5
6
7
8import { NativeModules, NativeEventEmitter, } from 'react-native'; const PushEventEmitter = NativeModules.PushEventEmitter; const emitterManager = new NativeEventEmitter(PushEventEmitter);
订阅通知和移除通知:
复制代码
1
2
3
4
5
6
7
8
9
10componentDidMount() { subscription = emitterManager.addListener( 'EventReminder', (reminder) => console.log('JavaScript接收到通知:'+reminder.name) ); } componentWillUnmount(){ subscription.remove();// 移除通知 }
调用测试:
复制代码
1PushEventEmitter *eventEmitter = [PushEventEmitter allocWithZone:nil];
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持靠谱客。
最后
以上就是时尚钢笔最近收集整理的关于Reactnative-iOS回调Javascript的方法的全部内容,更多相关Reactnative-iOS回调Javascript内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复