reactjs 在React中处理iframe,带引用

dced5bon  于 2022-12-12  发布在  React
关注(0)|答案(1)|浏览(223)

我尝试在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方法传递加载的内容,以便对加载的内容执行操作?

41ik7eoe

41ik7eoe1#

下面是引用的工作方式:

<MyComponent ref={(c) => { this.myComponent = c; }} />

MOUNTED组件之后,您可以访问组件本身及其方法:

this.myComponent.myMethod();

相关问题