将TypeScript回调函数提升到窗口对象

时间:2018-12-18 23:57:24

标签: reactjs typescript

我得到了一个工作正常的HTML页面,该页面具有JS代码,如下所示:

<script type="text/javascript">
    function nativeThingEventHandler(event) {
        console.log("event received: " + event);
    }

    window.onload = function() {
        if (typeof nativeThing !== "undefined") {
            console.log("Native thing was found");      
            nativeThing.setListener("nativeThingEventHandler");
        }
    }
</script>

其中nativeThing是执行填充的HTML外部对象,然后调用nativeThingEventHandler(如您所见,它在JS代码的顶层定义)回调。我需要将此HTML页面集成到React Typescript项目中,而我是TypeScript的新手。我在实现nativeThingEventHandler函数时遇到麻烦,因此nativeThing可以找到它,所以当nativeThing对象将事件发送回时,我总是遇到错误。我该如何在Typescript中定义事件处理程序,以便在构建项目后可以在JS代码的顶层找到它?

编辑以进行澄清::nativeObject的API期望在setListener方法中使用一个字符串,然后期望在该函数的顶层具有与该字符串同名的函数。 Javascript(不在其他任何函数中)。因此,这个问题专门与如何编写打字稿功能有关,一旦编译,它将导致该功能位于javascript的顶层。

1 个答案:

答案 0 :(得分:2)

一个丑陋的解决方法是手动将回调函数分配给window以下的变量:

import { nativeThingEventHandler } from 'somewhere';

(window as any).nativeThingEventHandler = nativeThingEventHandler;