React-Native RCTEventEmitter (OC方法调用RN方法)

React-Native RCTEventEmitter (OC方法调用RN方法)

需要从iOS向RN 发送一个通知,这时就会用到RCTEventEmitter.

我直接把代码贴出来:

//.h
+ (void)postNotiToReactNative:(NSString *)type args:(id)args;
//.m
RCT_EXPORT_MODULE();

- (NSArray<NSString *> *)supportedEvents {
    return @[@"SpotifyHelper"]; //这里返回的将是你要发送的消息名的数组。
}
- (void)startObserving
{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(emitEventInternal:)
                                                 name:@"event-emitted"
                                               object:nil];
}
- (void)stopObserving
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)emitEventInternal:(NSNotification *)notification
{
    [self sendEventWithName:@"SpotifyHelper"
                       body:notification.object];
}

+ (void)postNotiToReactNative:(NSString *)type args:(id)args{
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    dic[@"type"] = type;
    dic[@"args"] = args;
    [[NSNotificationCenter defaultCenter] postNotificationName:@"event-emitted" object:dic];
}

注意

一旦RCT_EXPORT_MODULE();声明该类是EXPORT_MODULE,那么该类的实例已经创建好了.如果你在其他地方创建这个类的实例(alloc 或 new),会导致,RN不能正确识别该类的实例.

对应的 RN 代码:

'use strict';

import React,{Component} from 'react';
import {
  ·
  ·
  ·
  NativeModules,
  NativeEventEmitter,
} from 'react-native';

import Main from './app/HJMain';

var nativeBridge = NativeModules.RNIOSExportJsToReact;//你的类名
const NativeModule = new NativeEventEmitter(nativeBridge);

export default class Haojia extends React.Component {

  render() {
    return (
        <Main />
    );
  }

  componentDidMount(){
    this.subscription = NativeModule.addListener('SpotifyHelper',(data)=>this._getNotice(data));
  }

  _getNotice (body) {//body 看你传什么
      //一系列操作
  }

  componentWillUnmount() {
    //删除监听
    this.subscription.remove()
  }

}

在OC需要的地方加上RNIOSExportJsToReact(参数)就可以调用RN的方法了

以上是OC 调用 RN方法的代码,完毕!

猜你喜欢

转载自blog.csdn.net/m18510011124/article/details/78979672
今日推荐