繁体   English   中英

从React TypeScript组件调用外部Javascript函数

[英]Call external Javascript function from react typescript components

我有一个带有打字稿的react redux应用程序。 所以场景是这样的,我有一个包含一些javascript的index.cshtml文件。

<script type="text/javascript">
    function test() {
        alert('Function from index.html');
    }
</script>

现在在我的react组件上,在componentWillMount()函数中的Main.tsx上,我想调用测试函数。

componentWillMount() {
    window.test();
}

但这对我不起作用。 消息是测试在类型窗口上不存在

任何帮助是极大的赞赏。

您可以像这样扩展Window接口:

interface Window {
    test(): void;
}

在模块中执行此操作时,需要确保它是要扩展的全局Window接口:

declare global {
    interface Window {
        test(): void;
    }
}

这为编译器提供了类型实现。

我建议在这里使用一些Utility类。 据我了解,您需要一些可以在其他组件中使用的功能。 因此,最好的方法是使用静态方法创建Util类。 或类似这样的模块:

export default {
  test() {
    console.log('foo'); 
  }, ...

};

如果您确定您具有全局变量。 您可以在键入文件夹中键入自定义文件。

interface Window {
    test: () => void
}

如果使用eslint,还应该将test设置为globals config选项。

暂无
暂无

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

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