React Native下的webview高度自适应

1,816 阅读1分钟

背景

  • webview容器的高度,跟随渲染html页面的高度自动拉伸撑开;若webview容器的高度不跟随html页面的高度变化,则会在webview上显示一个滚动条去滑动页面;

  • 目标是使webview的高度与内部html页面的高度一致,这样就不会在webview上产生滚动条

方案

  1. 获取html页面的高度与宽度
  • 页面注入js
  • 在html5页面load加载完成阶段去获取页面的高度与宽度,这里的单位是px
  • 将获取的高度与宽度回传给RN,高度命名为pageHeight 宽度命名为pageWidth
  1. 计算实际webview容器的高度dp
  • 获取rn webview容器的宽度,一般为屏幕的宽度,这里webviw容器的宽度命名为webviewWidth

  • px与dp的转换:rn的单位是dp,所以这里需要有一个px与dp的转换

  • 高度命名为webviewHeight

  • webviewHeight(dp) / pageHeight(px) = webviewWidth(dp) / pageWidth(px)

代码

注入的js

window.addEventListener('load', function() {
    setTimeout(function() {
        // 获取html页面高度
        var pageHeight = document.body.scrollHeight;
        // 获取html页面宽度
        var pageWidth = document.body.clientWidth;
        // 将高度和宽度回传给RN
        window.ReactNativeWebView.postMessage(JSON.stringify({
            params: {
                height: pageHeight,
                width: pageWidth
            }
        }))
    }, 1000);
})

计算webview容器的高度dp,这里假设场景为webview容器的宽度为屏幕的宽度

function computeHeight (pageWidth, pageHeight) {    // 获取webview容器的宽度dp  const { width: webviewWidth } = Dimensions.get('window');    // 根据html页面的高度(px)和宽度(px)计算webview实际应该渲染的高度dp  const webviewHeight = webviewWidth * pageHeight / pageWidth;    return parseInt(webviewHeight);}