在 Swift 中 React Native 发送事件到 JavaScript [英] React Native Sending Events to JavaScript in Swift

查看:49
本文介绍了在 Swift 中 React Native 发送事件到 JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Swift 中向 JavaScript 发送事件?

有 Objc 代码示例如何将事件发送到 JavaScript,但我需要快速完成?

There is examples of Objc code how to send event to JavaScript, but I need to do in swift?

#import "RCTBridge.h"
#import "RCTEventDispatcher.h"

@implementation CalendarManager

@synthesize bridge = _bridge;

- (void)calendarEventReminderReceived:(NSNotification *)notification
{
  NSString *eventName = notification.userInfo[@"name"];
  [self.bridge.eventDispatcher sendAppEventWithName:@"EventReminder"
                                               body:@{@"name": eventName}];
}

@end

推荐答案

我只是想自己解决这个问题.这实际上出奇的容易.这是我是如何做到的:

I was just trying to figure this out myself. It was actually surprisingly easy. Heres how I did it:

EventTests.m

#import "RCTBridgeModule.h"

@interface RCT_EXTERN_MODULE(EventTests, NSObject)

RCT_EXTERN_METHOD( testEvent:(NSString *)eventName )

@end

EventTests.Swift

import UIKit

@objc( EventTests )
class EventTests: NSObject {
    // Swift doesn't have synthesize - just define the variable
    var bridge: RCTBridge!

    @objc func testEvent( eventName: String ) {
        self.bridge.eventDispatcher.sendAppEventWithName( eventName, body: "Woot!" )
    }
}

MyModule.js

var React      = require( 'react-native' );
var EventTests = require( 'NativeModules' ).EventTests;

var {
    Component,
    NativeAppEventEmitter
} = React;

var testEventName = 'test';

class MyModule extends Component {

    constructor( options ) {
        super( options );

        // Register for our test event
        NativeAppEventEmitter.addListener( testEventName, ( body ) => {
            console.log( body );
        });

        // Call objective c function, which will emit our test event
        EventTests.testEvent( testEventName );
    }
}

module.exports = MyModule;

还要确保在桥接头中包含一些导入:

Also make sure to include a few imports in your bridging header:

#import "RCTBridge.h"
#import "RCTEventDispatcher.h"

这篇关于在 Swift 中 React Native 发送事件到 JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆