簡體   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