如何全局访问 App() 的 属性(在 React App 中,来自 pyodide)

How to access a property of App() globally (in React App, from pyodide)

我已经在 React 应用程序中实现了 pyodide like so

在上面 link 示例中的 src/App.js 中,假设我想从 script.py 访问 App() 中的 someProperty

const App = () => {
  const [output, setOutput] = useState("(loading...)");
  const [someProperty, setSomeProperty] = useState("Initial state");  // this one
  const runScript = code => {
    window.pyodide.loadPackage([]).then(() => {
  ...

在pyodide的正常情况下,我会使用import js从python like in the docs.

访问javascript范围

The JavaScript scope can be accessed from Python using the js module (see Using Javascript objects from Python). This module represents the global object window that allows us to directly manipulate the DOM and access global variables and functions from Python.

但是,属性在App()里面,不是直接在window下面。

如何从 script.py 访问 App() 中的 someProperty

换句话说,App()位于window属性之下的哪里?甚至可以全局访问 App() 的属性吗?

您应该能够创建一个可以访问这些局部变量的 JS 对象

let my_module = {
  someProperty : function(){
    return someProperty;
  }
};

然后您可以注册为 Python 模块,

pyodide.registerJsModule("my_js_module", my_module);

所以它可以导入为,

from my_js_module import someProperty

documentation for more details。这仅适用于 pyodide 的开发版本或即将发布的 0.17.0 版本。