我尝试在React组件中设置iframe的内容。我有一个组件,其中包含一个handleStatementPrint
函数,该函数必须在iframe完成加载时调用。该函数必须打印加载的iframe内容-使用url this.props.pdfs.url
访问的pdf文件。已经加载了iframe内容,我可以在iframe中看到pdf文件。我知道我需要使用componentDidMount
,但是不知道在这里写什么。
组件必须具有iframe内容:
import React, { Component } from 'react'
import IframeComponent from './components/Iframe';
class MainComponent extends Component {
handleStatementPrint = () => {
const iframePdf = this.iframePdf.contentWindow;
if (this.iframePdf !== undefined) {
const iframePdf = this.iframePdf.contentWindow;
iframePdf.print();
}
}
render () {
return (
<div className="container">
{
this.props.pdfs &&
<iframe
ref={(frame) => { this.iframePdf = frame }}
src={this.props.pdfs.url}
title="iFramePdf"
type="application/pdf"
>
</iframe>
}
</div>
);
}
};
export default Statement;
I框架组件:
import React, { Component } from 'react'
class IframeComponent extends Component {
componentDidMount() {
// Load iframe content
}
render () {
return (
<div>
<Iframe />
</div>
);
}
};
export default Iframe;
我是试过这个例子的:
Basic react iframe with onLoad handler
Handling of iframes in React
Iframe内容来自fetch API,但我可以访问iframe,并可以看到使用ref完全加载了内容。问题:需要在componentDidMount
方法中加载内容,然后才能从另一个可以打印加载iframe内容的组件调用handleStatementPrint
函数。
问题:
1.那么如何正确地传递iframe内容和refs来加载componentDidMountmethod中的内容呢?
1.如何从 MainComponent 函数中的componentDidMount
方法传递加载的内容,以便对加载的内容执行操作?
1条答案
按热度按时间41ik7eoe1#
下面是引用的工作方式:
MOUNTED组件之后,您可以访问组件本身及其方法: