简体   繁体   English

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

[英]Automatically adjust height of iframe using React Hooks

I have been working on adjusting iframe height automatically.我一直在努力自动调整 iframe 高度。

The solutions with the problem are not working in React Hooks.该问题的解决方案在 React Hooks 中不起作用。

I have read Setting iframe height to scrollHeight in ReactJS and Adjust width and height of iframe to fit with content in it .我已阅读Setting iframe height to scrollHeight in ReactJS调整 iframe 的宽度和高度以适应其中的内容 I have explored additional posts and tried several times for almost a week.我已经探索了其他帖子并尝试了几次几乎一个星期。 However, I have not found a proper way to figure this out.但是,我还没有找到正确的方法来解决这个问题。

I simplified what I have tried.我简化了我所尝试的。 My code 我的代码

Apart from my code, I also tried iframeResizer.min.js , yet it is not working.除了我的代码,我还尝试iframeResizer.min.js ,但它不起作用。 I believe it is because react generates dynamically.我相信这是因为反应动态生成。 I found iframe-resizer-react and tried but I have not found a way to solve it.我找到了iframe-resizer-react并尝试了,但我还没有找到解决它的方法。

Can anybody have the same situation?任何人都可以有同样的情况吗? How can I adjust iframe height automatically in React Hooks?如何在 React Hooks 中自动调整 iframe 高度?

from Setting iframe height to scrollHeight in ReactJS :设置 iframe 高度到 ReactJS 中的 scrollHeight

Use the onLoad() handler from the iframe to ensure that the content has loaded before you try to resize it - if you try to use React's lifecycle methods like componentDidMount() you run the risk of the content not being present yet.使用 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: You will run into issues with cross-origin policy if the iframe is in a different domain. PS:如果 iframe 在不同的域中,您将遇到跨域策略问题。

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

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