javascript - React Typescript,从外部脚本调用函数

标签 javascript typescript dom react-tsx global-functions

在我的 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/

相关文章:

javascript - 日期组件 Angular 2

c# - 是否可以在 ASP.NET 应用程序中打开 Word 文档

javascript - 如何将 typescript 文件导入脚本标签

html - 使用 Chrome 调试 React TypeScript .tsx 文件 - Webpack

javascript - D3v4 插入新节点

javascript - 如何让setState立即生效?

javascript - 在 native 钩子(Hook)之前加载可安装的钩子(Hook)

javascript - typescript 编译取决于文件的顺序

javascript - 如何抓取内容

javascript - 如何创建每个图表具有不同系列数的同步 Highcharts