- 由于以下原因,问题的典型解决方案在 React 中不起作用 它动态生成的组件结构和事件模型,而不是 传统的静态 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
):解决方案的可能部分是监听
load
事件iframe
,但以与 React 兼容的方式。
在 React 中有没有办法将 iframe
的高度设置为其可滚动内容的高度?
我的代码:
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>
);
}
}
最佳答案
这是答案,但首先有两件重要的事情。
- iframe 必须是
render()
方法中的根组件 - 必须从
onLoad
事件中捕获高度(如果完全加载则在 iframe 中捕获一次)
完整代码如下:
import React, { Component, PropTypes } from 'react'
import ReactDOM from 'react-dom'
export default class FullheightIframe extends Component {
constructor() {
super();
this.state = {
iFrameHeight: '0px'
}
}
render() {
return (
<iframe
style={{maxWidth:640, width:'100%', height:this.state.iFrameHeight, overflow:'visible'}}
onLoad={() => {
const obj = ReactDOM.findDOMNode(this);
this.setState({
"iFrameHeight": obj.contentWindow.document.body.scrollHeight + 'px'
});
}}
ref="iframe"
src="http://www.example.com"
width="100%"
height={this.state.iFrameHeight}
scrolling="no"
frameBorder="0"
/>
);
}
}
关于javascript - 在 ReactJS 中将 iframe 高度设置为 scrollHeight,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42042901/