How to access native UI components' instance methods in React Native

落爺英雄遲暮 提交于 2019-12-18 11:02:13

问题


We can control custom native UI components' properties by exporting native properties using RCT_EXPORT_VIEW_PROPERTY.

But how to export instance methods of native UI components?


回答1:


Thanks to @alinz's suggestion.

This can be done within the custom native component's view manager.

  1. Obj-c side: In the native view manager expose a native method like this:

The key is to pass in the reactTag which is the reference to the native component.

MyCoolViewManager.m:

RCT_EXPORT_METHOD(myCoolMethod:(NSNumber *)reactTag callback:(RCTResponseSenderBlock)callback) {
  [self.bridge.uiManager addUIBlock:^(RCTUIManager *uiManager, RCTSparseArray *viewRegistry) {
    MyCoolView *view = viewRegistry[reactTag];
    if (![view isKindOfClass:[MyCoolView class]]) {
      RCTLogMustFix(@"Invalid view returned from registry, expecting MyCoolView, got: %@", view);
    }
    // Call your native component's method here
    [view myCoolMethod];
  }];
}
  1. JS side: Add API in the react component class:

MyCoolView.js:

var React = require('react-native');
var NativeModules = require('NativeModules');
var MyCoolViewManager = NativeModules.MyCoolViewManager;
var findNodeHandle = require('findNodeHandle');

class MyCoolView extends React.Component{
    // ...
    myCoolMethod() {
        return new Promise((resolve, reject) => {
            MyCoolViewManager.myCoolMethod(
                findNodeHandle(this),
                (error, result) => {
                    if (error) {
                        reject(error);
                    } else {
                        resolve(result);
                    }
                }
            );
        });
    }
}



回答2:


I'm not an Objective C expert but a Swift developer.

I better use this way just for readability (maybe there are drawbacks in Obj-C?):

  • In Manager: store a reference to your view in an instance private property
  • it will then help to call your view's method

Obj-C side - component manager:

@implementation RNAnalogClockManager {
  RNAnalogClock* _AnalogClock;
}

RCT_EXPORT_MODULE()

- (UIView *)view
{
  // keep a reference to the view before returning it
  _AnalogClock = [[RNAnalogClock alloc] init];
  return _AnalogClock;
}

// export method and easily call view method 
RCT_EXPORT_METHOD(startRealTime) {
  [_AnalogClock startRealTime];
};

JS side remains the same

NOTE: I don't need callback in my example but it does not change the principle it is just another parameter.



来源:https://stackoverflow.com/questions/31857583/how-to-access-native-ui-components-instance-methods-in-react-native

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