原生与ReactNative使用通知进行传值

一、先在Xcode中创建发送通知文件,继承RCTEventEmitter,添加代理RCTBridgeModule,若使用pod导入的,会出现RCTEventEmitter not find ,此时只需要将头文件改成#import 即可
.h

#import 
NS_ASSUME_NONNULL_BEGIN
@interface WSNativeToReact : RCTEventEmitter
+ (void)postNotiNativeToReact:(NSString *)msg info:(NSString *)info;
@end
NS_ASSUME_NONNULL_END

.m

#import "WSNativeToReact.h"

@implementation WSNativeToReact

RCT_EXPORT_MODULE()//实现了RCTBridgeModule协议,我们的类需要包含RCT_EXPORT_MODULE()宏

- (NSArray *)supportedEvents {
    return @[@"WSNativeToReactNotiMothed"]; //这里返回的将是你要发送的消息名的数组。可以添加多个
}
- (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:@"WSNativeToReactNotiMothed"
                       body:notification.object];
}
+ (void)postNotiNativeToReact:(NSString *)msg info:(NSString *)info{
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    dic[@"msg"] = msg;
    dic[@"info"] = info;
    [[NSNotificationCenter defaultCenter] postNotificationName:@"event-emitted" object:dic];
}


@end

二、ReactNative代码

var WSNativeToReact = NativeModules.WSNativeToReact;
const myNativeEvt = new NativeEventEmitter(WSNativeToReact);  //创建自定义事件接口
componentDidMount(){

    if (Platform.OS === 'ios') {
      this.subscription = myNativeEvt.addListener('WSNativeToReactNotiMothed',(data)=>this._getNotice(data));
    }else{

    }
  }

  _getNotice (body) {//body 看你传什么
      //取出原生传过来的内容
      return Alert.alert(body.msg + body.info);

  }

  componentWillUnmount() {
    if (Platform.OS === 'ios') {
      //删除监听
      this.subscription.remove()
    }else{

    }
  }

你可能感兴趣的:(原生与ReactNative使用通知进行传值)