python 如何在React中运行Pyscript?

k2arahey  于 2023-03-21  发布在  Python
关注(0)|答案(2)|浏览(157)

我正在尝试在NextJS中使用PyScript,但我看到了几个错误。我不知道如何使用PyScript的React组件。有人成功地在ReactJS中使用PyScript吗?谢谢,

const Home: NextPage = () => {
  return (
    <div>
      <Head>
        <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
        <script defer src="https://pyscript.net/alpha/pyscript.js"></script>
      </Head>
      <div className="mx-auto container">
        <py-repl></py-repl>
        <py-script>
          import datetime as dt
          pyscript.write(‘today’, dt.date.today().strftime(‘%A %B %d, %Y’))
          def compute_pi(n):
              pi = 2
              for i in range(1,n):
                  pi *= 4 * i ** 2 / (4 * i ** 2 - 1)
              return pi
          pi = compute_pi(100000)
          pyscript.write(‘pi’, f’π is approximately {pi:.3f}’)
        </py-script>
      </div>
    </div>
  )
}

错误1。

Type error: Property 'py-repl' does not exist on type 'JSX.IntrinsicElements'.

错误2.

Unhandled Runtime Error
Error: Hydration failed because the initial UI does not match what was rendered on the server.
See more info here: https://nextjs.org/docs/messages/react-hydration-error

错误3.上述<py-script>导致

JsException(PythonError: Traceback (most recent call last): File "/lib/python3.10/site-packages/_pyodide/_base.py", line 429, in eval_code .run(globals, locals) File "/lib/python3.10/site-packages/_pyodide/_base.py", line 300, in run coroutine = eval(self.code, globals, locals) File "", line 2, in File "", line 129, in write AttributeError: 'NoneType' object has no attribute 'innerHTML' )
qlvxas9a

qlvxas9a1#

你可以设置python脚本到dangerouslySetInnerHTML

<div
  dangerouslySetInnerHTML={{
    __html: `<py-script>
    from datetime import datetime
    now = datetime.now()
    now.strftime("%m/%d/%Y, %H:%M:%S")
    </py-script>`,
  }}
/>

或者
PyScript-React尚未发布,但您可以关注它-https://github.com/Py4Js/PyScript-React

7kqas0il

7kqas0il2#

import React from 'react';
import Head from 'next/head';

const Sample = ()  => {
    return (
        <div>
            <Head>
                <link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" />
                <script defer src="https://pyscript.net/latest/pyscript.js"></script>
            </Head>
            <py-config></py-config>
            <py-script>
                print('Hello, World!')
            </py-script>
        </div>
    );
}

export default Sample;

相关问题