iOS端 RCTEventEmitter 使用 Native发送通知消息到ReactNative

iOS 向ReactNative 发送通知事件

[self.bridge.eventDispatcher sendAppEventWithName:@"EventReminder_BarcodeScanSuccessForRN"

的时候会提示

'sendDeviceEventWithName:body:'is deprecated: SubclassRCTEventEmitterinstead

查看源码发现,DeviceEventEmitterNativeAppEventEmitter 均已经被遗弃。
DeviceEventEmitter源码描述

/**
 * Deprecated - subclass NativeEventEmitter to create granular event modules instead of
 * adding all event listeners directly to RCTDeviceEventEmitter.
 */

NativeAppEventEmitter源码描述

/**
 * Deprecated - subclass NativeEventEmitter to create granular event modules instead of
 * adding all event listeners directly to RCTNativeAppEventEmitter.
 */

同时都推荐使用NativeEventEmitter子类
在0.28版本之后,iOS向Js端发射消息的 思路如下
Natived端,新版本模块类头文件必须继承自RCTEventEmitter
1.-(NSArray *)supportedEvents;中设置所支持的通知的名称
2.- (void)startObserving; Native端开启通知
3.RN使用NativeEventEmitter.addListener模块监听通知
4.RN在 componentWillUnmount 中remove移除通知
5.- (void)stopObserving Native端移除通知

Native部分
.h

#import "RCTEventEmitter.h"

@interface MallManageAPI : RCTEventEmitter 

.m

-(NSArray *)supportedEvents {
return@[@"EventReminder_CollectionProductSuccessForRN"];
}
- (void)startObserving {
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(CollectionProductSuccessForRNAction:)
                                                 name:@"CollectionProductSuccessForRN"
                                               object:nil];
  }

- (void)CollectionProductSuccessForRNAction:(NSNotification*)notification {
    
    dispatch_async(dispatch_get_main_queue(), ^{
    [self sendEventWithName:@"EventReminder_CollectionProductSuccessForRN" body:nil];
    });

}

- (void)stopObserving {
[[NSNotificationCenterdefaultCenter]removeObserver:selfname:@"CollectionProductSuccessForRN"object:nil];
}

RN部分

import React, { Component } from 'react';
import {
    NativeModules,
    Platform,
    //NativeAppEventEmitter,
    NativeEventEmitter
} from 'react-native';
var NativeModulesByIOS = NativeModules.MallManageAPI;

const NativeNotificationMoudule = new NativeEventEmitter(NativeModulesByIOS)

 componentWillMount() {
        console.log('开始订阅通知...');
        if (Platform.OS === 'ios') {
            subscription = NativeNotificationMoudule.addListener(
                'EventReminder_CollectionProductSuccessForRN',
                (reminder) => {
                    this._onRefresh()
                }
            );
        } else {
        }
    }

componentWillUnmount() {
        if (Platform.OS === 'ios') {
            subscription.remove();
        } else {
        }
    }

你可能感兴趣的:(iOS端 RCTEventEmitter 使用 Native发送通知消息到ReactNative)