Android、IOS主动发事件给React Native

IOS(Swift版本)

//RNEventEmitter.m

#import 
#import 

@interface RCT_EXTERN_MODULE(RNEventEmitter, NSObject)
@end
//RNEventEmitter.swift
import Foundation

@objc(RNEventEmitter)
class RNEventEmitter: RCTEventEmitter {
    
    //提供出EventName
    override func supportedEvents() -> [String]! {
        return ["UnReadMsgCountEvent"]
    }

    override func startObserving() {
        NotificationCenter.default.addObserver(self, selector: #selector(emitEventInternal(_:)), name: NSNotification.Name(rawValue: "event-emitted"), object: nil)
    }
    
    override func stopObserving() {
        NotificationCenter.default.removeObserver(self)
    }
    
    func emitEventInternal(_ notification: NSNotification)  {
        let eventName: String = notification.userInfo?["eventName"] as! String
        print("send event to RN: \(self.bridge) \(eventName) \(notification.userInfo)")
        self.sendEvent(withName: eventName, body: notification.userInfo)
    }

    @objc func notifiyRN(_ eventName: String, parameters: [String: Any] = [:] ) {
        var newParams: [String: Any] = parameters
        newParams["eventName"] = eventName
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "event-emitted"), object: self, userInfo: newParams)
    }
}
import {
  NativeEventEmitter,
  NativeModules
} from 'react-native'

....
componentDidMount(){
    const { RNEventEmitter } = NativeModules
    const eventEmitter = new NativeEventEmitter(RNEventEmitter);
    this.emitter = eventEmitter.addListener("UnReadMsgCountEvent", (data) => {
      console.log("ios 收到通知了:内容是:", data && data.unReadMsgCount)
    });
}
 componentWillUnmount() {
    this.emitter.remove();
  }
....
RNEventEmitter().notifiyRN("UnReadMsgCountEvent", parameters: ["unReadMsgCount": number]) })

IOS中使用RCTEventEmitter, 直接调用方法self.sendEvent(..)无效,RN会收不到事件. self.sendEvent(..)底层调用的self.bridge enqueueJSCall.会发现bridge = nil. 这里有个坑. 我们应该使用加载RN自构建的实例. 一种解决办法是在startObserving在给实例添加通知.实际调用发送事件事件时候,触发通知. 另外一种办法实现该类的单例.

Android

 WritableMap map = Arguments.createMap();
        map.putInt("unReadMsgCount", badgeCount);
        getReactInstanceManager().getCurrentReactContext()
                .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
                .emit("UnReadMsgCountEvent", map);
import {
  DeviceEventEmitter
} from 'react-native'
...
componentDidMount(){
  this.emitter = DeviceEventEmitter.addListener("UnReadMsgCountEvent",(data) => {
        console.log("android 收到通知了:内容是: ", data && data.unReadMsgCount);
        this.updateMailBoxBadge(data)
      })
}

componentWillUnmount() {
  this.emitter.remove();
}
...

参考:
1、RCTEventEmitter bridge is not set
2、ReactNative之EventEmitter

你可能感兴趣的:(Android、IOS主动发事件给React Native)