【问题标题】:Automatically adjust height of iframe using React Hooks使用 React Hooks 自动调整 iframe 的高度
【发布时间】:2021-07-16 23:17:58
【问题描述】:

我一直致力于自动调整 iframe 高度。

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

我已阅读 Setting iframe height to scrollHeight in ReactJSAdjust width and height of iframe to fit with content in it。我已经探索了其他帖子并尝试了几次几乎一个星期。但是,我还没有找到正确的方法来解决这个问题。

我简化了我的尝试。 My code

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

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

【问题讨论】:

    标签: javascript html reactjs iframe react-hooks


    【解决方案1】:

    来自Setting iframe height to scrollHeight in ReactJS

    使用 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 位于不同的域中,您将遇到跨域策略问题。

    【讨论】:

    • 非常感谢您的帮助,但它似乎对我不起作用。我没有任何问题,但问题是 iframe 没有显示整个页面。你可以聊天看看我的当前页面吗?
    • 我在控制台日志中没有错误。根据示例,我确实使用FrameWrapper Function 中的iframe 使用src={http://localhost:3000/employees/1} 在本地显示另一个页面
    • 这不适用于跨域,当您尝试从不同的来源访问文档时会引发 cors 错误。
    猜你喜欢
    • 2011-08-23
    • 1970-01-01
    • 1970-01-01
    • 2013-10-28
    • 2014-04-25
    • 2020-04-13
    • 1970-01-01
    • 1970-01-01
    • 2011-11-25
    相关资源
    最近更新 更多