对于第一个创建 Swift 类(例如YourModule.swift)
//
// YourModule.swift
//
@objc(YourModule)
class YourModule: NSObject {
@objc func callNativeEvent(callback:RCTResponseSenderBlock)
-> Void {
// Here you can do your work and pass an object to the callback function.
// You can save assign a `callback` to the class property (e.g self.eventCallback = callback)
// and invoke that self.eventCallback after the asynchronous code ol somewhere else
NSObject *obj = [[NSObject alloc] init]; // your object here
callback([NSNull(), obj]);
// or if you want to return an error
// callback(["Error calling NativeEvent", NSNull()]);
// I'm not sure that RCTResponseSenderBlock works the same as in previous react-native versions. Maybe now you can pass an Object instead of an Array.
}
}
创建一个 Bridge 文件(例如YourModuleBridge.m)
//
// YourModuleBridge.m
//
#import <Foundation/Foundation.h>
#import "UIKit/UIKit.h"
#import <React/RCTBridgeModule.h>
@interface RCT_EXTERN_MODULE(YourModule, NSObject)
RCT_EXTERN_METHOD(callNativeEvent:(RCTResponseSenderBlock)callback);
@end
另外,如果您的项目中不存在Bridging-Header 文件,则需要它。
//
// YourModule-Bridging-Header.h
//
#ifndef YourModule_Bridging_Header_h
#define YourModule_Bridging_Header_h
#if __has_include("RCTBridgeModule.h")
#import "RCTBridgeModule.h"
#else
#import <React/RCTBridgeModule.h>
#endif
#endif /* YourModule_Bridging_Header_h */
来自 JS
import { NativeModules } from 'react-native';
const YourModule = NativeModules.YourModule;
...
YourModule.callNativeEvent((error, response) => {
console.log('Error', error, 'Response', response);
});