我已经在 React 应用程序中实现了 pyodide like so .
在上面链接的示例中的 src/App.js
中,假设我在 App()
中有我想要的 someProperty
从 script.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/