如何在 Swift 中向 JavaScript 发送事件?
有 Objc 代码示例如何将事件发送到 JavaScript,但我需要在 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
最佳答案
我只是想自己解决这个问题。这实际上出奇的容易。这是我的做法:
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;
还要确保在桥接 header 中包含一些导入:
#import "RCTBridge.h"
#import "RCTEventDispatcher.h"
关于swift - React Native 在 Swift 中向 JavaScript 发送事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31870775/