[英]Call external Javascript function from react typescript components
[英]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.