温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Reactnative-iOS回调Javascript的方法

发布时间:2020-09-25 13:03:03 来源:脚本之家 阅读:165 作者:FlyElephant 栏目:移动开发

Reactnative可以调用原生模块,原生模块也可以给JavaScript发送事件通知.最好的方法是继承RCTEventEmitter.自定义继承自PushEventEmitter的子类RCTEventEmitter.

#import <Foundation/Foundation.h>
#import <React/RCTBridgeModule.h>
#import <React/RCTEventEmitter.h>

@interface PushEventEmitter : RCTEventEmitter <RCTBridgeModule>

- (void)addEventReminderReceived:(NSNotification *)notification;

@end

实现supportedEvents方法

#import "PushEventEmitter.h"

@implementation PushEventEmitter

+ (id)allocWithZone:(NSZone *)zone {
  static PushEventEmitter *sharedInstance = nil;
  static dispatch_once_t onceToken;
  dispatch_once(&onceToken, ^{
    sharedInstance = [super allocWithZone:zone];
  });
  return sharedInstance;
}

RCT_EXPORT_MODULE();

- (NSArray<NSString *> *)supportedEvents
{
  return @[@"EventReminder"];
}

- (void)addEventReminderReceived:(NSNotification *)notification {
  [self sendEventWithName:@"EventReminder" body:@{@"name": @"FlyElephant"}];
}

@end

React native 设置:

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

const PushEventEmitter = NativeModules.PushEventEmitter;

const emitterManager = new NativeEventEmitter(PushEventEmitter);

订阅通知和移除通知:

  componentDidMount() {
    subscription = emitterManager.addListener(
      'EventReminder',
      (reminder) => console.log('JavaScript接收到通知:'+reminder.name)
    );

  }
  componentWillUnmount(){
    subscription.remove();// 移除通知
  }

调用测试:

PushEventEmitter *eventEmitter = [PushEventEmitter allocWithZone:nil];

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI