假设我有以下 Swift 类:
@objc(ExampleClass)
class ExampleClass: NSObject {
init() {}
@objc func exampleMethod(_ message: String, _ properties: [String: Any]? = nil) -> Void {}
}
以及以下 header :
#import <Foundation/Foundation.h>
#import <React/RCTBridgeModule.h>
@interface RCT_EXTERN_MODULE(ExampleClass, NSObject)
RCT_EXTERN_METHOD(exampleMethod:(NSString *)name (NSDictionary *)properties)
@end
然后我使用以下 React Native 代码调用它:
import { NativeModules } from 'react-native'
NativeModules.ExampleClass.exampleMethod('example', {'hello': 'world'})
这会导致以下错误消息:
ExceptionsManager.js:73 Exception 'exampleMethod: is not a recognized Objective-C method.' was thrown while invoking trackEvent on target SegmentTracker with params (
"example",
{
hello = world;
}
)
这样调用时:
NativeModules.ExampleClass.exampleMethod('example')
结果:
ExceptionsManager.js:73 Exception 'exampleMethod: is not a recognized Objective-C method.' was thrown while invoking trackEvent on target SegmentTracker with params (
"example"
)
我有两个问题: 1) 如何将 JSON 从 React Native 传递到 Swift? 2) 如何在 RCT_EXTERN_METHOD 中正确允许可选参数?如果这不可能,我该如何处理有时我想传递第二个参数,有时又不想传递的情况?
最佳答案
您可以尝试使用 NSDictionary 类型的属性,以便它适合界面。它可能类似于:
关于objective-c - 将可选的 JSON 从 react-native 传递给 Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50402121/