React Native Sending Events to JavaScript in Swift

后端 未结 2 465
孤独总比滥情好
孤独总比滥情好 2021-02-06 11:52

How can I send event\'s to JavaScript in Swift?

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

         


        
2条回答
  •  不思量自难忘°
    2021-02-06 12:24

    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"
    

提交回复
热议问题