如何在 React Native 中访问原生 UI 组件的实例方法 [英] How to access native UI components' instance methods in React Native

查看:51
本文介绍了如何在 React Native 中访问原生 UI 组件的实例方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们可以通过使用 RCT_EXPORT_VIEW_PROPERTY 导出原生属性来控制自定义原生 UI 组件的属性.

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

但是如何导出原生 UI 组件的实例方法?

But how to export instance methods of native UI components?

推荐答案

感谢 @alinz建议.

这可以在自定义本机组件的视图管理器中完成.

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

  1. Obj-c 端:在本机视图管理器中公开这样的本机方法:

关键是传入reactTag,它是对原生组件的引用.

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端:在react组件类中添加API:

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 中访问原生 UI 组件的实例方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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