簡體   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