【问题标题】:Invoking function defined within iframe from parent using React Ref使用 React Ref 从父级调用 iframe 中定义的函数
【发布时间】:2020-12-10 18:06:14
【问题描述】:

我的 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 中定义的函数?

我有this sandbox that I've been playing with

【问题讨论】:

    标签: javascript reactjs typescript iframe react-ref


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多