[英]React Native: How to export a method with a return value?
What is the best way to export a method with a return value in React Native? 在React Native中导出具有返回值的方法的最佳方法是什么?
I know there is RCT_EXPORT_METHOD
, but that only works for methods that are (void)
and therefore don't return anything. 我知道有
RCT_EXPORT_METHOD
,但这只适用于(void)
方法,因此不返回任何内容。 Preferably I don't need to export the whole class, just a few methods. 我最好不需要导出全班,只需几种方法。
The other option would be to have a callback, but I would like to avoid that if possible as it bloats up the code too much in my use case. 另一个选择是有一个回调,但我想避免这种情况,因为它在我的用例中夸大了代码。 Are there are any other options I might have missed?
我可能错过了其他任何选择吗?
You can also now use promises, which tend to look a little nicer in your JS. 你现在也可以使用promises,它往往在你的JS中看起来更好一些。
Objective C: 目标C:
RCT_REMAP_METHOD(getThing, resolver: (RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject)
{
if( condition ) {
NSString *thingToReturn = @"ALL OK";
resolve(thingToReturn);
} else {
reject([NSError errorWithDomain:@"com.companyname.app" code:0 userInfo:@{ @"text": @"something happend" }]);
}
}
Then in JS: 然后在JS中:
async onPress() {
try {
const status = await CustomModule.getThing();
// do something with status
} catch(e) {
console.error(e);
}
}
Seems no way yet. 似乎还没有。 That should be a feature to support.
这应该是一个支持的功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.