简体   繁体   English

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

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

In my react application, I fetch a custom javascript file from the server and append it as a script tag to the body of document . 在我的react应用程序中,我从服务器获取一个自定义javascript文件,并将其作为script标签附加到document的正文中。

this newly added custom file contains a method called manipulator . 这个新添加的自定义文件包含一个称为manipulator的方法。 Now in one of the components, I want to call that function. 现在,在其中一个组件中,我想调用该函数。 As I know the function should exist in the window global object. 据我所知,该函数应该存在于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)
}

But here I get the compiler error 但是这里我得到编译器错误

Property 'manipulator' does not exist on type 'Window'.ts(2339) 类型“ Window” .ts(2339)上不存在属性“ manipulator”

which is totally logical, but I did not find a way to create an extended interface for window or any other way to tell the compiler that there is an optional function in window called manipulator . 这是完全合乎逻辑的,但是我没有找到一种为window创建扩展接口的方法,也没有找到任何其他方法来告诉编译器window中有一个称为manipulator的可选函数。

Any help is appreciated. 任何帮助表示赞赏。

  ----------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);
      });
    });
  }

You can add it to the Window interface from inside a TypeScript module (ts or tsx) like this: 您可以从TypeScript模块(ts或tsx)内部将其添加到Window界面,如下所示:

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

Or you can create a global global.d.ts (name doesn't matter, only that it's inside your source directory), containing this: 或者,您可以创建一个包含以下内容的全局global.d.ts (名称无关紧要,只不过它位于源目录中):

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

Be aware that this makes the function available everywhere, also before the script is initialized. 请注意,这会使函数在任何地方都可用,甚至在脚本初始化之前。

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

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