iOS 原生Swift 向 React Native JS 發(fā)送事件

1需求

在React Native中需要接收原生模塊發(fā)出的事件來(lái)更新UI操作

2思路分析

iOS從原生向React Native發(fā)送Event會(huì)比Android復(fù)雜一些。 您無(wú)法獲得直接獲得EventEmitter的實(shí)例,并無(wú)法像在Android上那樣輕松地使用它來(lái)發(fā)送消息。 您需要將RCTEventEmitter子類(lèi)化,然后實(shí)現(xiàn)supportedEvents方法,該方法應(yīng)返回受支持事件的數(shù)據(jù)。 之后您將可以使用sendEventWithName本身。

3實(shí)現(xiàn)

  1. 在橋接文件 bridging header 中引入
#import <React/RCTEventEmitter.h>
  1. 在你的 .m 執(zhí)行文件中聲明可調(diào)用的方法:
#import <React/RCTBridgeModule.h>
@interface RCT_EXTERN_MODULE(RNSwiftExample, NSObject)
RCT_EXTERN_METHOD(doSomethingThatHasMultipleResults: (RCTResponseSenderBlock *)errorCallback)
@end
  1. 在需要發(fā)事件的原生模塊中的類(lèi)繼承 RCTEventEmitter
    在.swift文件中重載 RCTEventEmitter 的方法
@objc(RNSwiftExample)
class RNSwiftExample: RCTEventEmitter {
  
  // Returns an array of your named events
  override func supportedEvents() -> [String]! {
    return ["MyEvent"]
  }
  
  // Takes an errorCallback as a parameter so that you know when things go wrong.  
  // This will make more sense once we get to the Javascript
  @objc func doSomethingThatHasMultipleResults(
    _ errorCallback: @escaping RCTResponseSenderBlock) {
    
    
    let names = ["Anna", "Alex", "Brian", "Jack"]
    for name in names {
          // You send an event with your result instead of calling a callback
        self.sendEvent(withName: "MyEvent", body: name)
    }
  }
  1. 在React Native中生成調(diào)用的方法
import { NativeEventEmitter, NativeModules } from 'react-native';

let {
    RNSwiftExample
} = NativeModules

module.exports = {
    emitter: new NativeEventEmitter( RNSwiftExample ),

    doSomethingThatHasMultipleResults( callback )
    {
        this.emitter.addListener(
            'MyEvent',
            name => callback( null, name )
        );

        RNSwiftExample.doSomethingThatHasMultipleResults( callback )
    },
}
  1. 也可以在其他的JS模塊中調(diào)用改方法,然后建立監(jiān)聽(tīng)事件
import { NativeEventEmitter, NativeModules } from 'react-native';
let {
    RNSwiftExample
} = NativeModules
const emitter = new NativeEventEmitter(RNSwiftExample);

{
    this.subscription = emitter.addListener('MyEvent', (value)=>{
      console.warn("MyEvent",value);
      //update your UI
    });
}
  1. 記住要取消監(jiān)聽(tīng)
this.subscription.remove();
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容