简体   繁体   中英

Call external Javascript function from react typescript components

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 component, on Main.tsx in componentWillMount() function I want to call test function.

componentWillMount() {
    window.test();
}

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

Any help is greatly appreciated.

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 compiler.

I suggest to use here some Utility class. As I understand you need some functions which you can use in other components. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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