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

4

我有一个使用 TypeScript 的 React Redux 应用程序。

情况是这样的,我有一个包含一些 JavaScript 的 index.cshtml 文件。

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

现在在我的React组件中,我想在Main.tsx的componentWillMount()函数中调用test函数。

componentWillMount() {
    window.test();
}

但这对我没有起作用。 错误信息是“test”不属于window类型。 非常感谢任何帮助。
3个回答

6
你可以像这样扩展Window接口:
interface Window {
    test(): void;
}

当你在模块内进行这个操作时,需要确保你正在扩展全局的 Window 接口:

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

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

0
我建议在这里使用一些实用类。据我所知,您需要一些可以在其他组件中使用的函数。因此,最好的方法是创建具有静态方法的Util类或类似的模块:
export default {
  test() {
    console.log('foo'); 
  }, ...

};

0

如果你确定有一个全局变量,你可以在打字文件夹中输入自定义文件。

interface Window {
    test: () => void
}

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接