react使用iframe标签引入网页自适应高度

react使用iframe标签引入网页自适应高度

定义Iframe 函数组件(Iframe函数组件可提为高阶组件提高代码复用性)

const Iframe = props => {
  window.onresize=function(){ props.load()}
	return (
		<iframe id="iframeId" onLoad={ props.load} src={ props.src} width={ props.width}  height={`${ props.height}px`} frameborder="0" scrolling ="no"/>
	);
};

监听获取页面高度

 state = {
    height: ' ',
  };
 
  load = () => {
    var ifm = document.getElementById("iframeId");
    // console.log(ifm.contentDocument.body.scrollHeight)
    var subWeb = document.frames ? document.frames["iframeId"].document : ifm.contentDocument;
    if (ifm != null && subWeb != null) {
      this.setState({
        height: subWeb.body.scrollHeight - 30
      })
    }
  }

render渲染页面

  render() {
    return (

          <Iframe src="./index.html" width="100%" load={this.load} height={this.state.height} />
    );
  }

版权声明:本文为Tyler_YC原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。