最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

reactjs - Call external Javascript function from react typescript components - Stack Overflow

programmeradmin9浏览0评论

I have a react redux application with typescript. So the scenario is like this, I have an index.cshtml file that includes some javascript.

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

Now on my react ponent, on Main.tsx in ponentWillMount() function I want to call test function.

ponentWillMount() {
    window.test();
}

but this is not working for me. The message is test doesn't exist on type window

Any help is greatly appreciated.

I have a react redux application with typescript. So the scenario is like this, I have an index.cshtml file that includes some javascript.

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

Now on my react ponent, on Main.tsx in ponentWillMount() function I want to call test function.

ponentWillMount() {
    window.test();
}

but this is not working for me. The message is test doesn't exist on type window

Any help is greatly appreciated.

Share Improve this question asked Nov 30, 2018 at 12:49 RapiraRapira 831 silver badge7 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 6

You can extend the Window interface like this:

interface Window {
    test(): void;
}

When you are doing this within a module, you need to ensure it is the global Window interface you are extending:

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

This provides the type implementation to the piler.

I suggest to use here some Utility class. As I understand you need some functions which you can use in other ponents. So, the best way to do it is to create Util class with statics methods. or some module like this:

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

};

If you are sure that you have a global variable. You can type your self define file in typing folder.

interface Window {
    test: () => void
}

if you use eslint, you should also set test to globals config option.

发布评论

评论列表(0)

  1. 暂无评论