欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Reactnative-iOS回调Javascript的方法

程序员文章站 2022-04-11 09:13:22
reactnative可以调用原生模块,原生模块也可以给javascript发送事件通知.最好的方法是继承rcteventemitter.自定义继承自pusheventem...

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];

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