繁体   English   中英

使用 React Hooks 自动调整 iframe 的高度

[英]Automatically adjust height of iframe using React Hooks

我一直在努力自动调整 iframe 高度。

该问题的解决方案在 React Hooks 中不起作用。

我已阅读Setting iframe height to scrollHeight in ReactJS调整 iframe 的宽度和高度以适应其中的内容 我已经探索了其他帖子并尝试了几次几乎一个星期。 但是,我还没有找到正确的方法来解决这个问题。

我简化了我所尝试的。 我的代码

除了我的代码,我还尝试iframeResizer.min.js ,但它不起作用。 我相信这是因为反应动态生成。 我找到了iframe-resizer-react并尝试了,但我还没有找到解决它的方法。

任何人都可以有同样的情况吗? 如何在 React Hooks 中自动调整 iframe 高度?

设置 iframe 高度到 ReactJS 中的 scrollHeight

使用 iframe 中的 onLoad() 处理程序以确保在尝试调整内容之前已加载内容 - 如果您尝试使用 React 的生命周期方法(如 componentDidMount() ),您将面临内容尚不存在的风险。

function FrameWrapper() {
  const ref = React.useRef();
  const [height, setHeight] = React.useState("0px");
  const onLoad = () => {
    setHeight(ref.current.contentWindow.document.body.scrollHeight + "px");
  };
  return (
    <iframe
      ref={ref}
      onLoad={onLoad}
      id="myFrame"
      src="http://demo_iframe.htm"
      width="100%"
      height={height}
      scrolling="no"
      frameBorder="0"
      style={{
        maxWidth: 640,
        width: "100%",
        overflow: "auto",
      }}
    ></iframe>
  );
}

PS:如果 iframe 在不同的域中,您将遇到跨域策略问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM