繁体   English   中英

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

[英]React Typescript, Call a function from external script

在我的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)
}

但是这里我得到编译器错误

类型“ 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);
      });
    });
  }

您可以从TypeScript模块(ts或tsx)内部将其添加到Window界面,如下所示:

declare global {
  interface Window {
    manipulator: () => void;
  }
}

或者,您可以创建一个包含以下内容的全局global.d.ts (名称无关紧要,只不过它位于源目录中):

declare interface Window {
  manipulator: () => void;
}

请注意,这会使函数在任何地方都可用,甚至在脚本初始化之前。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM