在我的 React 应用程序中,我从服务器获取自定义 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)
}
但是这里我得到了编译器错误
Property 'manipulator' does not exist on type 'Window'.ts(2339)
这完全合乎逻辑,但我没有找到为 window
创建扩展接口(interface)的方法或任何其他方式告诉编译器 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);
});
});
}
最佳答案
您可以像这样从 TypeScript 模块(ts 或 tsx)中将其添加到 Window
界面:
declare global {
interface Window {
manipulator: () => void;
}
}
或者您可以创建一个全局的global.d.ts
(名称并不重要,只要它在您的源目录中即可),包含以下内容:
declare interface Window {
manipulator: () => void;
}
请注意,这使得函数在任何地方都可用,在脚本初始化之前也是如此。
关于javascript - React Typescript,从外部脚本调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55892506/