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

reactjs - Call react component function from javascript - Stack Overflow

programmeradmin0浏览0评论

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.

发布评论

评论列表(0)

  1. 暂无评论