javascript - React Typescript,从外部脚本调用函数
问题描述
在我的反应应用程序中,我从服务器获取一个自定义 javascript 文件并将其作为script
标签附加到document
.
这个新添加的自定义文件包含一个名为manipulator
. 现在在其中一个组件中,我想调用该函数。据我所知,该函数应该存在于window
全局对象中。
if(documnet.getElementById('customJsId')){ // check if the script tag exists in document
window.manipulator(); // which I get Property 'iframeManipulator' does not exist on type 'Window'.ts(2339)
}
但是在这里我得到编译器错误
'Window'.ts(2339) 类型上不存在属性'manipulator'
这是完全合乎逻辑的,但我没有找到一种方法来创建扩展接口window
或任何其他方法来告诉编译器在window
被调用中有一个可选函数manipulator
。
任何帮助表示赞赏。
----------Just in case--how the script is added to document--------------
loadProjectCustomJS() {
runInAction(async () => {
thisfetchProjectJs().then((doc) => {
const body: HTMLBodyElement = document.getElementsByTagName('body')[0];
const customjs: HTMLScriptElement = document.createElement('script');
customjs.type = 'text/javascript';
customjs.id = 'customJsId'
customjs.src = doc.get('resourceUrl');
body.appendChild(customjs);
});
});
}
解决方案
Window
您可以从 TypeScript 模块(ts 或 tsx)内部将其添加到界面,如下所示:
declare global {
interface Window {
manipulator: () => void;
}
}
或者您可以创建一个全局global.d.ts
(名称无关紧要,只是它在您的源目录中),其中包含:
declare interface Window {
manipulator: () => void;
}
请注意,这使得函数在任何地方都可用,在脚本初始化之前也是如此。
推荐阅读
- node.js - nodejs中html内的数组映射错误
- python - 如何绘制多个树状图?
- flutter - 如何将 AdobeXD 精确原型转换为颤振
- java - 三个单元如何在 Analogic 中并行工作传入的工件载体?
- dataframe - 两个数据帧之间的欧式距离
- regex - 如何匹配以反斜杠开头的字符串,后跟 / 之类的问号?
= 用正则表达式 - python - 根据键在字典中查找值
- python - Python(CPython)中的最大可解析行长度是多少?
- python - 通过 python 3 在用户文件夹中搜索光栅图像文件的最有效方法是什么?
- .net - 在 Webview2 中使用 ExecuteScriptAsync 从网站中提取数据