【发布时间】: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 中定义的函数?
【问题讨论】:
标签: javascript reactjs typescript iframe react-ref