React Native调用iOS原生UI组件的方法

在RN中文网的原生UI组件章节: iOS Android,我们知道如何封装原生UI组件给Javascript 端使用,如何导出属性,如何设置事件回调、样式等,但是View难免会有一些公有方法,翻遍官方文档却怎么也找不到相关描述,我在这里做个导出UI组件方法的记录。

假如现在有个自定义View “LLCustomView” 想要封装给React Native的js调用。

#import 

@interface LLCustomView : UIView

- (void)textFunc;

@end
#import "LLCustomView.h"

@implementation LLCustomView

- (void)textFunc {
    NSLog(@"%s", __FUNCTION__);
}

@end
  • 新建一个文件继承自RCTViewManager的文件,文件名为视图名称+Manager,
  • 在实现文件里添加RCT_EXPORT_MODULE()标记宏,让模块接口暴露给JavaScript
  • 实现-(UIView )view方法,并返回组件视图
    原生View的frame或backgroundColor属性这里就不用设置了,为了两端统一,JavaScript 端的布局属性会覆盖原生属性。
#import 

@interface LLCustomViewManager : RCTViewManager

@end
#import "LLCustomViewManager.h"
#import 
#import "LLCustomView.h"

@interface LLCustomViewManager ()

@property (nonatomic, strong) LLCustomView *customView;

@end


@implementation LLCustomViewManager

RCT_EXPORT_MODULE()

- (UIView *)view {
    _customView = [[LLCustomView alloc] initWithFrame:CGRectZero];
    return _customView;
}

RCT_EXPORT_METHOD(textFunc:(nonnull NSNumber *)reactTag) {
    [self.bridge.uiManager addUIBlock:^(__unused RCTUIManager *uiManager, NSDictionary *viewRegistry) {
        LLCustomView *view = viewRegistry[reactTag];
        if (![view isKindOfClass:[LLCustomView class]]) {
            RCTLogError(@"Invalid view returned from registry, expecting LLCustomView, got: %@", view);
        } else {
            dispatch_async(dispatch_get_main_queue(), ^{
                LLCustomView *bannerView = (LLCustomView *)viewRegistry[reactTag];
                [bannerView textFunc];
            });
        }
    }];
}

@end

JavaScript

当js端需要封装时:


image.png

1和6对应原生模块;
4为直接导出的组件名称,4和5名称必须一致;
注意当js端需要封装UI组件时,我们在requireNativeComponent增加第二个参数从 null 变成了用于封装的组件CustomView。这使得 React Native 的底层框架可以检查原生属性和包装类的属性是否一致,来减少出现问题的可能。

使用UIManager模块的dispatchViewManagerCommand方法,JS端可以调用Native的View方法,

  • findNodeHandle方法是在React中定义,可以找到组件实例的reactTag(执行在JS端),UIManager可以把调用命令分发到Native端对应的组件类型的ViewManager,再通过ViewManager调用View组件实例的对应方法。
  • 通过UIManager.LLCustomView.Commands找到模块数据结构,不过新版提示这个将被废弃,使用UIManager.getViewManagerConfig('LLCustomView').Commands代替。
  • 第三个参数,要传给原生UI组件方法的参数

CustomView.js

import React, {Component} from 'react';
import PropTypes from 'prop-types';
import {requireNativeComponent, findNodeHandle, UIManager} from 'react-native';
import console = require('console');

var LLCustomView = requireNativeComponent('LLCustomView', CustomView);

export default class CustomView extends Component {

    static propTypes = {};
    static defaultProps = {};

    render() {
        return ;
    }

    textFunc = () => {
        UIManager.dispatchViewManagerCommand(
            findNodeHandle(this),
            UIManager.getViewManagerConfig('LLCustomView').Commands.textFunc,
            null
        );
    };
}

调用

控制台输出

-[LLCustomView textFunc]

你可能感兴趣的:(React Native调用iOS原生UI组件的方法)