React通过iframe方式引入html,并解决高度自适应问题

1,951 阅读1分钟

前言

最近有个需求,将微信公众号链接利用iframe嵌入到网页中。本以为将网页引入来后,取消滚动条,height调成100%就ok了,没想到还有坑。

iframe引入方案

方案一 引入整个html文件(需要配置webpack)

import test from "./test.html";

<iframe
          title="resg"
          ref={iframeRef}
          frameBorder="0"
          srcDoc={test}
          style={{ width: '100%', overflow: 'hidden' }}
          sandbox="allow-same-origin allow-scripts allow-popups allow-forms"
          scrolling="no"
        />

React项目中没有解析html类型的loader,所以需要我们自己手动添加html-loader

运行 npm run eject,将原本被封装到脚手架当中的命令弹射出来,然后就可以在项目的目录下看到很多配置文件.

打开webpack.config.js文件

image.png

module中添加如下代码

{
          test: /\.html$/,
          use: [
                {
                  loader: require.resolve('html-loader')
                }
               ]
       },

方案二 把html文件源码转换成字符串引入

利用 html压缩工具 ,将html文件压缩,引入字符串

const html = "<!DOCTYPE html><html><head><meta charset="utf-8"><title>iframe</title></head><body><h1>test</h1></body></html>";
 
export default html;

由于我的html文件是通过插件下载下来的,结构上压缩后有点问题,所以我采用了方式一

解决iframe高度自适应,无滚动条问题

使用useEffect钩子监听iframeload事件,并在事件处理程序中计算出iframe的高度。

import React, { useEffect, useRef } from 'react';

const Iframe = ({ src }) => {
  const iframeRef = useRef(null);

  useEffect(() => {
    const iframe = iframeRef.current;
    const handleIframeLoad = () => {
      iframe.style.height = iframe.contentWindow.document.body.scrollHeight + 'px';
    };
    iframe.addEventListener('load', handleIframeLoad);
    return () => {
      iframe.removeEventListener('load', handleIframeLoad);
    };
  }, []);

  return (
    <iframe
      title="iframe"
      ref={iframeRef}
      src={src}
      frameBorder="0"
      scrolling="no"
      style={{ width: '100%', overflow: 'hidden' }}
    />
  );
};

export default Iframe;

END

  • 希望这篇文章可以帮助到有需要的小伙伴们,有问题可以评论或私信我呀🤞🤞