在ReactJS中将iframe的高度设置为scrollHeight [英] Setting iframe height to scrollHeight in ReactJS
问题描述
- 由于以下原因,该问题的典型解决方案在React中不起作用 它动态生成的组件结构和事件模型,而不是 传统静态HTML:
- The typical solution to the problem doesn't work in in React due to its dynamically generated component structure and event model, as opposed to traditional static HTML:
脚本:
<script>
function resizeIframe(obj) {
obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';
}
</script>
html:
<iframe src="..." frameborder="0" scrolling="no" onload="resizeIframe(this)" />
-
有一个npm包
react-iframe
,但它似乎未完成 (仅接受道具url
,width
,height
):There is a npm package
react-iframe
, but it looks unfinished (accepts only propsurl
,width
,height
):https://www.npmjs.com/package/react-iframe
解决方案的可能部分是监听
iframe
,但以与React兼容的方式.The likely part of the solution is to listen to the
load
event of theiframe
, but in a way that is compatible with React.React中是否可以将
iframe
的高度设置为其可滚动内容的高度?Is there a way in React to set the height of an
iframe
to the height of its scrollable contents?我的代码:
import React, { Component } from 'react' import ReactDOM from 'react-dom' import Iframe from 'react-iframe' export default class FullheightIframe extends Component { componentDidMount() { console.log("IFRAME DID MOUNT"); } renderReactFrame() { return ( <Iframe url="http://www.example.com" width="100%" height="100%" onLoad={()=>{console.log("IFRAME ON LOAD")}}></Iframe> ); } renderHTMLFrame() { return ( <iframe onLoad={(loadEvent)=>{ // NOT WORKING var frameBody = ReactDOM.findDOMNode(this).contentDocument.body; // contentDocument undefined // NOT WORKING obj.nativeEvent.contentWindow.document.body.scrollHeight // contentWindow undefined }} ref="iframe" src="http://www.example.com" width="100%" height="100%" scrolling="no" frameBorder="0" /> ); } render() { return ( <div style={{maxWidth:640, width:'100%', height:'100%', overflow:'auto'}}> {this.renderHTMLFrame()} </div> ); } }
推荐答案
您要执行的操作是在componentDidMount中,运行脚本以设置高度. [如果要加载外部内容,则可能要在IFrame上添加事件侦听器,以等待加载外部内容.]
What you want to do is in your componentDidMount, run the script to set the height. [If you are loading external content, you might want to add event listener on the IFrame to wait until the external content is loaded.]
componentDidMount() { const obj = ReactDOM.findDOMNode(this); obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px'; }
还有另一种更反应"的方式-将高度存储在状态中.
There is another, more "reacty" way of doing this - where you would store the height in state.
componentDidMount() { const obj = ReactDOM.findDOMNode(this); this.setState({iFrameHeight: obj.contentWindow.document.body.scrollHeight + 'px'}); }
,然后在您的渲染器中:
and then in your render:
render() { return ( <div style={{maxWidth:640, width:'100%', height:this.state.iFrameHeight, overflow:'auto'}}> {this.renderHTMLFrame()} </div> ); }
这篇关于在ReactJS中将iframe的高度设置为scrollHeight的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!