当前位置: 移动技术网 > 移动技术>移动开发>IOS > Reactnative-iOS回调Javascript的方法

Reactnative-iOS回调Javascript的方法

2019年07月23日  | 移动技术网移动技术  | 我要评论

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

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网