react-native webview自适应高度异常,长空白

燕正卿
2023-12-01
import React, {useState} from 'react';
import {WebView} from 'react-native-webview';

const baseScript = () => {
  return `
  var height = null;
  function changeHeight() {
    if (document.body.scrollHeight != height) {
      height = document.body.scrollHeight;
      if (window.postMessage) {
        window.ReactNativeWebView.postMessage(JSON.stringify({ type: 'setHeight', height: height,}));
      }
    }
  }
  changeHeight();
  
  true;
`;
};

const AutoHeightWebView = ({
  htmlText = '',
  customStyle = '',
  style = {},
  customHeight = 200,
  minHeight,
  androidHardwareAccelerationDisabled = false,
}) => {
  const ref = React.useRef();
  const [height, setHeight] = useState(customHeight);
  let defaultStyle = `
  <style type="text/css">
    body { background-color: #ffffff; margin: 0; }
    div { padding-bottom: 20px; }
    p { margin: 16px 0; color: #5d5d5d; }
  </style>
  `;
  let html = `
    <!DOCTYPE html>
    <html>
      <meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0">
      ${customStyle ? customStyle : defaultStyle}
      <body>
      <div id="_div">
        ${htmlText}
        </div>
      </body>
    </html>
  `;

  const handleMessage = e => {
    try {
      const action = JSON.parse(e.nativeEvent.data);
      if (
        action.type === 'setHeight' &&
        action.height > 0 &&
        action.height !== height
      ) {
        setHeight(
          minHeight
            ? action.height < minHeight
              ? minHeight
              : action.height
            : action.height,
        );
      }
    } catch (error) {
      // pass
    }
  };

  return (
    <WebView
      ref={ref}
      containerStyle={[{height: height}, style]}
      incognito={false}
      originWhitelist={['*']}
      automaticallyAdjustContentInsets={false}
      source={{html: html, baseUrl: ''}}
      scalesPageToFit={false}
      scrollEnabled={false}
      showsHorizontalScrollIndicator={false}
      showsVerticalScrollIndicator={false}
      onMessage={handleMessage}
      androidHardwareAccelerationDisabled={androidHardwareAccelerationDisabled}
      onLoadEnd={() => {
        ref.current.injectJavaScript(baseScript());
      }}
    />
  );
};

export default AutoHeightWebView;

 类似资料: