react-native 自定义view向js暴露接口方法

解决方法参考:http://stackoverflow.com/questions/31857583/how-to-access-native-ui-components-instance-methods-in-react-native


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:(nonnull <span style="font-family: Arial, Helvetica, sans-serif;">NSNumber *)reactTag callback:(RCTResponseSenderBlock)callback) {</span>
  [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);
                    }
                }
            );
        });
    }
}




你可能感兴趣的:(react-native)