调用内部函数从外部反应功能组件



如果我需要调用python ,我正在为python应用程序使用EEL

使用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

现在。。。我对通过python更新我的react内部状态(使用钩子(很感兴趣,我认为我可以在我的Component内部编写一个函数,并从这里更新状态,我知道这不是";反应方式";但有办法做到这一点吗?我认为使用useImperativeHandle可以工作,但我不确定

非常感谢

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

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

}

然后像一样呼叫

MyReactComponent.exposedFunction()

同样,这个解决方案没有遵循react风格和原则,但如果您需要将其集成到Eel或任何其他解决方案中,它是有效的

对于其他寻求答案的人,eel有一个特定的公开方法来处理react等框架附带的编译步骤。

来自鳗鱼示例07:

使用window.el.exposure(func,'func'(来规避npm运行构建代码对的破坏

因此eel.expose(my_javascript_function);,它将变成window.eel.expose(my_javascript_function, 'my_javascript_function');