Call external Javascript function from react components

前端 未结 4 1951
南旧
南旧 2020-12-08 14:32

Im not sure if this has been asked before or anybody has encountered the same issue on reactjs. So the scenario is like this, I have an index.html file that include

相关标签:
4条回答
  • 2020-12-08 14:34

    Try this solution to call global functions from React with TypeScript enabled:

    Either in index.html or some_site.js

    function pass_function(){
      alert('42');
    }
    

    Then, from your react component:

    window["pass_function"]();
    

    And, of course, you can pass a parameter:

    //react
    window["passp"]("react ts");
    
    //js
    function passp(someval) {
      alert(`passes parameter: ${someval}`);
    }
    
    0 讨论(0)
  • 2020-12-08 14:35

    In index.html

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

    In your component

    componentWillMount() {
      window.test();
    }
    
    0 讨论(0)
  • 2020-12-08 14:53

    So either you define the method on global scope (aka window). And then you can use it from any methods, being React or not.

    Or you can switch to module based paradigm and use require/import to get the module and use the function.

    For bigger projects the latter is better as it's scales, while if you need a demo or POC you can certainly hook all to global scope and it will work.

    More information about modules is at: http://exploringjs.com/es6/ch_modules.html

    0 讨论(0)
  • 2020-12-08 14:53

    You can attached your method to the global window object and than use it like that in your component:

    <button onClick={this.howItWorks} type="button" className='btn'>How it Works</button>
    
    howItWorks = () => {
      window.HowItWorksVideo();
    }
    
    0 讨论(0)
提交回复
热议问题