React Native: How to export a method with a return value?

帅比萌擦擦* 提交于 2021-02-07 04:46:10

问题


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

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?


回答1:


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

Objective 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:

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



回答2:


Try return values with Callbacks

RCT_EXPORT_METHOD(findEvents:(RCTResponseSenderBlock)callback)
{
  NSArray *events = ...
  callback(@[[NSNull null], events]);
}



回答3:


Seems no way yet. That should be a feature to support.



来源:https://stackoverflow.com/questions/29771622/react-native-how-to-export-a-method-with-a-return-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!