React Native -- iOS给React Native
1. 参考中文官网或者英文官网的代码如下:
给Javascript发送事件
即使没有被JavaScript调用,原生模块也可以给JavaScript发送事件通知。最好的方法是继承RCTEventEmitter,实现suppportEvents方法并调用self sendEventWithName:。
OC端:
RN端:
只是简简单单的几行代码,作为新手根本无法 calendarEventReminderReceived 这个方法到底如何使用?也没有明确的说明
2.下面我来完完整整的实现了一下iOS端给RN端发送事件:
iOS端:
// xxx.h
#import<React/RCTEventEmitter.h>
#import<React/RCTEventEmitter.h>
@interface RNPushEvent : RCTEventEmitter<RCTBridgeModule>
@end
//xxx.m
#import "RNPushEvent.h"
@implementation RNPushEvent
RCT_EXPORT_MODULE();
- (NSArray<NSString *> *)supportedEvents
{
return @[@"EventReminder"];
}
-(void)startObserving{
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(emitEventInternal:) name:@"event-emited" object:nil];
}
-(void)stopObserving{
[[NSNotificationCenter defaultCenter]removeObserver:self];
}
-(void)emitEventInternal:(NSNotification*)notification{
[self sendEventWithName:@"EventReminder" body:notification.userInfo];
}
+ (void)emitEventWithName:(NSString*)name andPayload:(NSDictionary*)payload
{
[[NSNotificationCenter defaultCenter] postNotificationName:@"event-emitted"
object:self
userInfo:payload];
}
@end
RN端:
import React,{Component} from 'react';
import {
·
·
·
NativeModules,
NativeEventEmitter,
} from 'react-native';
const {RNPushEvent} = NativeModules
const rnPushEventEmitter = new NativeEventEmitter(RNPushEvent)
componentDidMount() {
rnPushEventEmitter.addListener('EventReminder',(data)=> console.log("EventReminder:",data));
}
componentWillUnmount(){
this.rnPushEventEmitter.remove()
}
然后就是发送NSNotification的地方了,在需要传递事件的地方执行以下代码即可:
[[NSNotificationCenter defaultCenter]postNotificationName:@"event-emited" object:nil userInfo:@{@"name":@"notification coming "}];
大功告成~~
PS:第一次写,排版有点乱, 谅解下