自定义react-native-webview 一些配置

rn 通讯

https://blog.csdn.net/reylen/article/details/117256522

import React, {useState, useEffect} from 'react';
import {View, Text, BackHandler} from 'react-native';
import {Button} from 'react-native-elements';
import SafeAreaViewPlus from '../../components/common/SafeAreaViewPlus';
import {WebView} from 'react-native-webview';
import {useNavigation} from '@react-navigation/native';

let jsonToken = {
  // 传递给html的准备数据
  token: '2123444',
};
const WebViews = props => {
  let WebviewRef = null;
  const [webTitle, setWebTitle] = useState('加载中');
  const [canGoBack, setCanGoBack] = useState(false); // 是否返回
  const navigation = useNavigation();
  useEffect(() => {
    const backAction = () => {
      if (canGoBack) {
        WebviewRef.goBack();
        return true;
      } else {
        return false;
      }
    };
    const backHandler = BackHandler.addEventListener(
      'hardwareBackPress',
      backAction,
    );
    return () => backHandler.remove();
  }, [WebviewRef, canGoBack]);
  // 处理html到rn端的请求
  const callbackGetWebViewData = data => {
    if (data.type === 1) {
      setWebTitle(data.title);
    }
  };
  // rn发送方法(数据)到html端
  const handleInjectJavascript = data => {
    const injectJavascriptStr = `(function() {
      window.WebViewBridge.onMessage(${JSON.stringify(data)});
    })()`; // 拼接数据方法
    if (WebviewRef) {
      WebviewRef.injectJavaScript(injectJavascriptStr);
    } //   通过 injectJavaScript  将数据传递给WebView页面,并立即执行为js
  };
  return (
     {
        if (canGoBack) {
          WebviewRef.goBack();
        } else {
          navigation.goBack();
        }
      }}
      headerTitle={webTitle}>
       {
          // Keep track of going back navigation within component
          // console.log(navState);
          setCanGoBack(navState.canGoBack);
        }}
        // 允许文件上传
        // allowFileAccess={true}
        onLoadEnd={() => {
          console.log('加载成功');
          handleInjectJavascript(jsonToken);
        }}
        onError={() => {
          console.log('加载失败');
        }}
        ref={node => (WebviewRef = node)}
        onMessage={event => {
          let msg = JSON.parse(event.nativeEvent.data);
          callbackGetWebViewData(msg);
          // console.log('rn端数据...', msg);
        }}
        // style={{marginTop: 20, width: 400, height: 600}}
      />
    
  );
};
export default WebViews;

你可能感兴趣的:(自定义react-native-webview 一些配置)