React Native:如何导出具有返回值的方法? [英] React Native: How to export a method with a return value?

查看:67
本文介绍了React Native:如何导出具有返回值的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 React Native 中导出具有返回值的方法的最佳方法是什么?

What is the best way to export a method with a return value in React Native?

我知道有 RCT_EXPORT_METHOD,但这仅适用于 (void) 的方法,因此不返回任何内容.最好我不需要导出整个类,只需要导出几个方法.

I know there is RCT_EXPORT_METHOD, but that only works for methods that are (void) and therefore don't return anything. 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?

推荐答案

你现在也可以使用 promises,它在你的 JS 中看起来会更好一些.

You can also now use promises, which tend to look a little nicer in your JS.

目标 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" }]);
  }
}

然后在 JS 中:

async onPress() {
  try {
    const status = await CustomModule.getThing();
    // do something with status
  } catch(e) {
    console.error(e);
  }
}

这篇关于React Native:如何导出具有返回值的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆