React Native调用IOS原生控件的方法,非继承NSOb

2019-11-28  本文已影响0人  FMaarten

先不多说,先把原生的OC控件代码标出了

#import <UIKit/UIKit.h>
#import <React/RCTViewManager.h>

NS_ASSUME_NONNULL_BEGIN

@interface IOSWebView : RCTViewManager

@end

NS_ASSUME_NONNULL_END
#import "IOSWebView.h"
#import <WebKit/WebKit.h>
//iOS调用RN
#import <React/RCTEventDispatcher.h>
#import <React/RCTUIManager.h>

@interface IOSWebView ()

@property (nonatomic ,strong) WKWebView *webView;

@end

@implementation IOSWebView

RCT_EXPORT_MODULE();

- (UIView *)view
{
  WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
  webView.allowsBackForwardNavigationGestures = YES;
  self.webView = webView;
  return webView;
}

//reactTag是当前控件的tag值,不需要去管,releaseVLC是方法名,后面的one才是第一个参数,如果有几个参数,可以在后面继续添加
RCT_EXPORT_METHOD(releaseVLC:(nonnull NSNumber *)reactTag one:(NSString *)oneParam) {
  
  NSLog(@"reactTag = %@  secondParam = %@",reactTag,secondParam);
  
  [self.bridge.uiManager addUIBlock:^(__unused RCTUIManager * uiManager,NSDictionary *viewRegistry) {
    
    WKWebView *view = viewRegistry[reactTag];
    if (![view isKindOfClass:[WKWebView class]]) {
      RCTLogError(@"Invalid view returned from registry, expecting WKWebView, got: %@", view);
    } else {
      dispatch_async(dispatch_get_main_queue(), ^{
//        WKWebView * bannerView = (WKWebView *)viewRegistry[reactTag];
      });
    }
  }];
}

@end

下面的是RN的js代码调用IOS的原生方法

import React, { Component } from 'react';
import { StyleSheet, Text, View, TouchableOpacity, requireNativeComponent, UIManager, findNodeHandle } from 'react-native';

//IOSWebView这个是原生控件的Class名称,h5rn这是当前rn页面
var UIWebView = requireNativeComponent('IOSWebView', h5rn) ;

export default class h5rn extends Component<{}> {

  constructor(props) {
    super(props);
    this.state = {
    };
  }

  _back() {
    UIManager.dispatchViewManagerCommand(
        //this.refs["uiwebview"]这是当前UIWebView在页面上的属性,可以按自己想法随便写
        findNodeHandle(this.refs["uiwebview"]),
        //IOSWebView是原生控件的Class名称,releaseVLC是原生的方法名
        UIManager.getViewManagerConfig('IOSWebView').Commands.releaseVLC,
        //这个地方很重要,这个地方是入参,如果iOS原生没有参数,你传null,若有,这个地方必须是数组,参数放在数组中,数组的长度就是原生方法的参数个数,谨记
        ["2"]
      );
  }

  render() {
    return (
      <View style={{ flex: 1 }}>
        <View style={{ flex: 1 }}>
          <UIWebView ref={"uiwebview"} style={styles.IOSStyle}   />
          <TouchableOpacity style={{ with: gScreen.screen_width, height: 45 }} onPress={() => { this._back() }}>
            <Text>返回</Text>
          </TouchableOpacity>

        </View>
      </View>
    );
  }
}

var styles = StyleSheet.create({
  webview_style: {
  IOSStyle: {
    width: 300,
    height: 400,
  }
});

如有不对,请大家指教,谢谢大家

上一篇下一篇

猜你喜欢

热点阅读