简体   繁体   中英

Call external Javascript function from react components

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 includes some javascript. Now on my react component, I have a condition that will render only if the condition is true. This means that initially when my page loaded the component has not been rendered yet. When I toggle a button this is where that component gets rendered. That child component needs to call a javascript method that was included on my index.html. How should I do this?

Any help is greatly appreciated.

In index.html

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

In your component

componentWillMount() {
  window.test();
}

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}`);
}

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

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();
}

for typescript users, try this:

declare global {
    interface Window {
        externalMethod: (params: any) => void;
    }
}

then you would be able to call it like this in your react component

window.externalMethod(params)

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