admin管理员组

文章数量:1356219

I have one question because I'm not sure if that possible. I have ReactJS project that included some javascript functions.

I found solution to call javascript function from react ponents with window object but is it possible to call function from reactponents in javascript script?

For example I have definied function in React ponent. Is it possible to call that function in javascript?

Thank you.

I have one question because I'm not sure if that possible. I have ReactJS project that included some javascript functions.

I found solution to call javascript function from react ponents with window object but is it possible to call function from reactponents in javascript script?

For example I have definied function in React ponent. Is it possible to call that function in javascript?

Thank you.

Share Improve this question asked Mar 7, 2019 at 9:46 DevmastaDevmasta 5734 gold badges14 silver badges41 bronze badges 4
  • Is there a reason why you need to call a React ponent from a function? Can you provide the use case because the pattern doesn't seem correct and there's probably a better pattern for the use case – Kenneth Truong Commented Mar 7, 2019 at 9:50
  • delete method is in react ponent. I'm working on click event in javascript function that need to call that delete method from react ponent. – Devmasta Commented Mar 7, 2019 at 9:51
  • What do you mean in javascript? you mean node? This doesnt sound like a good way of doing this. – squeekyDave Commented Mar 7, 2019 at 9:54
  • 1 Can you provide example code? To give context that will make it easier to understand the use case – Kenneth Truong Commented Mar 7, 2019 at 9:55
Add a ment  | 

1 Answer 1

Reset to default 8

A function that is supposed to be used outside React application bundle should be exposed to global scope:

window.foo = () => { /* ... */ };

Then it can be accessed as such:

<script src="react-app-bundle.js"></script>
<script>
foo();
</script>

In case React application bundle is published as UMD module, it can export a function in entry point:

export const foo = () => { /* ... */ };

its namespace will be exposed to global scope when it's loaded via <script>:

<script src="react-app-bundle.js"></script>
<script>
ReactAppNamespace.foo();
</script>

This is the case for a lot of third-party React libraries, React itself exposes React global.

It's preferable to put all code that depends on React application internals to the application itself, so accessing globals is not needed.

本文标签: reactjsCall react component function from javascriptStack Overflow