javascript - 使用 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 中定义的函数?
解决方案
这是我自己想出来的。这个问题与我的预期有点无关,但我会发布以防其他人遇到这个问题。放置public/iframe.html
导致它找不到文件,我需要设置src={iframe.html}
但没有意识到public
搜索这些文件的默认位置。此外,调用 html 中的函数应该是onClick={() => this.state.iframeRef.current!.contentWindow!.sayHi()}
.
推荐阅读
- python - 如何有效地将数组解码为熊猫数据框中的列
- python - 一个热门编码器是行业规范,在训练/拆分之前或之后进行编码
- java - API 服务中的数据不更新,仅在清除缓存后更新
- mongoose - 如何防止猫鼬创建集合?
- .htaccess - 将单页限制为用户代理?
- javascript - 如果文本框 2 中有相同的多个值,则 jQuery 验证文本框 1
- node.js - NodeJS 中巨大的 JSON 对象处理
- google-cloud-platform - Google Cloud Billing:如何配置发送预算通知的时间
- sql - SQL Server 中的数学问题
- c++ - Microsoft Detours:缺少宏