简体   繁体   中英

calling function inside react functional component from outside

I'm using EEL for a python app, if I need call a python

with Eel I can call javascript functions directly from python

eel.expose(my_javascript_function);
function my_javascript_function(a, b, c, d) {
  if (a < b) {
    console.log(c * d);
  }
}
can be called from the Python side like this...

print('Calling Javascript...')
eel.my_javascript_function(1, 2, 3, 4)  # This calls the Javascript function

now...I'm interested in update my react inner state (using hooks) through python, I think that I could write a function inside my Component and update the state from here, I know that this is not the "react way" but is there a way to achieve this? I think that using useImperativeHandle could works but I'm not sure

thank you so much

this was more simple than I thought, just set to the component as a property,

function MyReactComponent(){
 useEffect(() => {
        MyReactComponent.exposedFunction = ()=>{
           //you can even set state here
        }
        // or expose in the window object
        window.MyReactComponent = MyReactComponent
    }, [])



}

and then call like

MyReactComponent.exposedFunction()

again, this solution is not following the react style and principles but it works if you need to integrate this to Eel or to any other solution

For others looking for an answer, eel has aa specific expose method for dealing with the compilation steps that come with frameworks like react.

From Eel Example 07 :

Use window.eel.expose(func, 'func') to circumvent npm run build code mangling

So instead of eel.expose(my_javascript_function); , it would become window.eel.expose(my_javascript_function, 'my_javascript_function');

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