繁体   English   中英

在内部调用 function 从外部反应功能组件

[英]calling function inside react functional component from outside

我将EEL用于 python 应用程序,如果我需要调用 python

使用 Eel,我可以直接从 python 调用 javascript 函数

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"但是有没有办法做到这一点? 我认为使用 useImperativeHandle 可以工作,但我不确定

太感谢了

这比我想象的要简单,只需将组件设置为属性,

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



}

然后像这样打电话

MyReactComponent.exposedFunction()

同样,此解决方案不遵循反应风格和原则,但如果您需要将其集成到 Eel 或任何其他解决方案,它可以工作

对于其他寻找答案的人,eel 有一个特定的暴露方法来处理诸如 react 之类的框架附带的编译步骤。

来自鳗鱼示例 07

使用 window.eel.expose(func, 'func') 来规避 npm 运行构建代码修改

所以代替eel.expose(my_javascript_function); ,它将变为window.eel.expose(my_javascript_function, 'my_javascript_function');

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM