首页 > 解决方案 > 使用 React Ref 从父级调用 iframe 中定义的函数

问题描述

我试图从父级调用的 React 代码中有一个 iframe。我为连接到 iframe 的 iframe 创建了一个 React Ref,但我不确定如何从 React 组件对 iframe 中的函数做出反应。这是一个简化的示例:

// App.tsx
import * as React from "react";
import "./styles.css";

interface Props {}

interface State {
  iframeRef: React.RefObject<HTMLIFrameElement>;
}

export default class App extends React.Component<Props, State> {

  /**
   * @inheritdoc
   */
  public constructor(props: Props) {
    super(props);
    this.state = {
        ...this.state,
        iframeRef: React.createRef()
    };
  }
  
  /**
   * @inheritdoc
   */
  public render() { 
    return (
    <div className="App">
      <h1>In component</h1>
      <iframe
        ref={this.state.iframeRef}
        title={"iframe"}
        src={"public/iframe.html"}
      />
    <button 
      onClick={() => this.state.iframeRef.current!.contentWindow!.document!.body!.sayHi()}
    >click me</button>
    </div>
  );
    }
}

这是在 iframe 中调用的 HTML 代码:

// public/iframe.html
<!DOCTYPE html>
<html>
  <body>
    in iframe
    <script>
      function sayHi() {
        alert("hello");
      }
    </script>
  </body>
</html>

我有两个问题。我看不到 src 文件中定义的 HTML,它只是一个带边框的空框。另一个问题是当我单击按钮时,我得到了_this2.state.iframeRef.current.contentWindow.document.body.sayHi is not a function一个有意义的错误,因为我不确定如何引用 iframe src 文件中定义的函数。

如何让 iframe 显示 src 文件的内容?以及如何访问我引用的 iframe 中定义的函数?

我有这个我一直在玩的沙盒

标签: javascriptreactjstypescriptiframereact-ref

解决方案


这是我自己想出来的。这个问题与我的预期有点无关,但我会发布以防其他人遇到这个问题。放置public/iframe.html导致它找不到文件,我需要设置src={iframe.html}但没有意识到public搜索这些文件的默认位置。此外,调用 html 中的函数应该是onClick={() => this.state.iframeRef.current!.contentWindow!.sayHi()}.


推荐阅读