gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 23:26:09 24 4
gpt4 key购买 nike

我一直致力于自动调整 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,但它不起作用。我相信这是因为 react 动态生成。我找到了 iframe-resizer-react 并尝试了,但我还没有找到解决它的方法。

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

最佳答案

来自 Setting iframe height to scrollHeight in ReactJS :

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.

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

关于javascript - 使用 React Hooks 自动调整 iframe 的高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67218249/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com