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

前端 未结 3 1198
梦谈多话
梦谈多话 2021-02-18 13:43

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

相关标签:
3条回答
  • 2021-02-18 13:55

    Try return values with Callbacks

    RCT_EXPORT_METHOD(findEvents:(RCTResponseSenderBlock)callback)
    {
      NSArray *events = ...
      callback(@[[NSNull null], events]);
    }
    
    0 讨论(0)
  • 2021-02-18 13:56

    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);
      }
    }
    
    0 讨论(0)
  • 2021-02-18 14:02

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

    0 讨论(0)
提交回复
热议问题