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

标签 reactjs pyodide

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

在上面链接的示例中的 src/App.js 中,假设我在 App() 中有我想要的 somePropertyscript.py 访问。

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访问javascript范围like in the docs .

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 版本。

关于reactjs - 如何全局访问 App() 的属性(在 React App 中,来自 pyodide),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66382887/

相关文章:

javascript - 如何动态改变backgroundImage?

javascript - Touchableopacity onpress 在 SVG 标签内不起作用

javascript - renderMenuItemChildren 中未定义“this”

javascript - pyscript 中没有名为 'theblockchainapi' 的模块

javascript - Pyodide Plotly 内存不足,内存访问越界

node.js - Socket.io 没有刷新 React 组件

javascript - Pyodide languagePluginLoader 未定义

python - 允许保留关键字作为 Python 中的方法

python - 是否可以使用 pyodide 的 wasm 在浏览器中构建 python wheel?

html - React 中的 SVG 图标不显示