RN原生封装组件

Android代码:

创建组件WebViewManager类

继承:extends SimpleViewManager

public class WebViewManager extends SimpleViewManager {

    //返回JS调用时候使用的名称
    @Override
    public String getName() {
        return "RCTWebView";

    }

    //用于创建初始化的实例控件对象
    @Override
    protected WebView createViewInstance(ThemedReactContext reactContext) {
        WebView webView = new WebView(reactContext);
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });
        return webView;
    }

    //设置RN中方法属性
    @ReactProp(name = "url")
    public void setUrl(WebView view, @Nullable String url) {
        view.loadUrl(url);
    }
    @ReactProp(name = "html")
    public void setHtml(WebView view, @Nullable String html) {
        view.loadData(html, "text/html; charset=utf-8", "UTF-8");
    }
}

创建ToastPackage.java类

public class ToastPackage implements ReactPackage {

        //创建原生模块
        @Override
        public List createNativeModules(ReactApplicationContext reactContext) {
            List list = new ArrayList();
            list.add(new ToastModule(reactContext));
            list.add(new CommunicationModule(reactContext));
            return list;
        }
    
        //创建原生视图
        @Override
        public List createViewManagers(ReactApplicationContext reactContext) {
            List list = new ArrayList<>();
            list.add(new WebViewManager());
            return list;
        }
}

在MainApplication.java类中:

		    @Override
		    protected List getPackages() {
		      return Arrays.asList(
		              new MainReactPackage(),new ToastPackage()
		      );
		    }

RN代码

创建WebExample.js

	    import PropTypes from "prop-types";
	    import { requireNativeComponent, ViewPropTypes } from "react-native";
	    
	    var iface = {
	      name: "WebView",
	      propTypes: {
	        url: PropTypes.string,
	        html: PropTypes.string,
	        ...ViewPropTypes // include the default view properties
	      }
	    };
	    
	    module.exports = requireNativeComponent("RCTWebView", iface, {
	      nativeOnly: {
	        testID: true,
	        renderToHardwareTextureAndroid: true,
	        accessibilityComponentType: true,
	        accessibilityLabel: true,
	        importantForAccessibility: true,
	        accessibilityLiveRegion: true,
	        onLayout: true
	      }
	    });

在你先要生成原生组件处:

    /**
     * Sample React Native App
     * https://github.com/facebook/react-native
     * @flow
     */
    
    import React, { Component } from "react";
    import { Button, StyleSheet, Text, View } from "react-native";
    import WebView1 from "./WebExample";
    
    export default class WebExampleDemo extends Component {
      render() {
        return (
          
            {/*  */}
            
          
        );
      }
    }

你可能感兴趣的:(RN原生封装组件)