我正在尝试在React组件中设置iframe的内容。我有一个组件,其中包含handleStatementPrint
函数,当iframe完成加载时必须调用该函数。该函数必须打印加载的iframe内容 - 使用url this.props.pdfs.url
访问的pdf文件。已加载iframe内容,我可以在iframe中看到pdf文件,但我需要使用refs传递iframe内容,但不知道如何正确执行此操作。我知道我需要使用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;
iframe组件 :
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
iframe内容来自fetch API,但我可以访问iframe,并且可以看到使用ref完全加载内容。问题:需要在componentDidMount
方法中加载该内容,然后才能从另一个可以打印加载的iframe内容的组件调用handleStatementPrint
函数。
问题:
那么如何使用refs正确传递iframe内容以加载componentDidMount方法中的内容?
如何从 MainComponent 函数中的componentDidMount
方法传递加载的内容,以便对加载的内容执行操作?
答案 0 :(得分:1)
这就是refs的工作原理:
<MyComponent ref={(c) => { this.myComponent = c; }} />
在组件安装完成后,您可以访问组件本身及其方法:
this.myComponent.myMethod();