w4t*_*4tw 3 html javascript iframe reactjs react-hooks
我一直致力于自动调整 iframe 高度。
该问题的解决方案在 React Hooks 中不起作用。
我已经阅读了在ReactJS中将iframe高度设置为scrollHeight和调整iframe的宽度和高度以适应其中的内容。我已经探索了更多的帖子,并在近一周的时间里尝试了几次。但是,我还没有找到正确的方法来解决这个问题。
我简化了我所尝试的。我的代码
除了我的代码之外,我也尝试过iframeResizer.min.js,但它不起作用。我相信这是因为反应是动态生成的。我发现iframe-resizer-react并尝试过,但还没有找到解决问题的方法。
有人可以有同样的情况吗?如何在 React Hooks 中自动调整 iframe 高度?
从在ReactJS中将iframe高度设置为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>
);
}
Run Code Online (Sandbox Code Playgroud)
PS:如果 iframe 位于不同的域中,您将遇到跨源策略问题。
| 归档时间: |
|
| 查看次数: |
17132 次 |
| 最近记录: |