RN

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

2019-05-14  本文已影响60人  FANTASIED

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

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

#import <UIKit/UIKit.h>

@interface LLCustomView : UIView

- (void)textFunc;

@end
#import "LLCustomView.h"

@implementation LLCustomView

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

@end
#import <React/RCTViewManager.h>

@interface LLCustomViewManager : RCTViewManager

@end
#import "LLCustomViewManager.h"
#import <React/RCTUIManager.h>
#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<NSNumber *, UIView *> *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方法,

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 <LLCustomView {...this.props} />;
    }

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

调用

<Button title='click' onPress={()=>{
          this.customViewRef && this.customViewRef.textFunc();
        }}/>

控制台输出

-[LLCustomView textFunc]
上一篇下一篇

猜你喜欢

热点阅读