可以做彩票网站的工作室,网页搜索是什么意思,照片网站怎么做,wordpress图下一篇迷途小书童的 Note 读完需要 6分钟 速读仅需 2 分钟 1 reactpy 介绍 reactpy 是一个用 Python 语言实现的 ReactJS 框架。它可以让我们使用 Python 的方式来编写 React 的组件#xff0c;构建用户界面。 reactpy 的目标是想要将 React 的优秀特性带入 Python 领域#xff0c;… 迷途小书童的 Note 读完需要 6分钟 速读仅需 2 分钟 1 reactpy 介绍 reactpy 是一个用 Python 语言实现的 ReactJS 框架。它可以让我们使用 Python 的方式来编写 React 的组件构建用户界面。 reactpy 的目标是想要将 React 的优秀特性带入 Python 领域包括组件化、虚拟 DOM、声明式编程等。它可以无缝集成到我们的 Python 后端应用中。 2 实现原理 reactpy 的核心原理是使用 JavaScript 编写的高效 DOM 操作库 InteractJS 与 Python 代码相连接。 InteractJS 负责实际的 DOM 操作实现类 React 的渲染和计算机制Python 端用类的方式定义组件通过 pyreact 接口与 InteractJSruntime 连接Python 端 state 或 props 变化时重新 render()并调用 rerender 将变化传给 JS 端InteractJS 通过 DOM diff 运算进行精确更新,重新渲染页面事件和数据从 JS 端传回 Python 端做处理 3 基本用法 使用之前我们需要安装一下 pip install reactpy reactpy 的用法与 React 非常类似。下面是一个简单示例 from reactpy import component, html, run# 这是一个定义应用程序显示内容(本例是一个一级标题)的方法component装饰器应用其上会将其转换为组件
component
def App():return html.h1(Hello, world!)# 将App方法作为参数启动 web server
run(App) 执行上述脚本在浏览器中打开链接 http://127.0.0.1:8000 ( http://127.0.0.1:8000 ) 有时候我们希望两个组件的状态始终保持一致。在下面的示例中2 个输入框共享相同的状态。状态通过父组件 SyncedInputs 共享。检查 value 和 set_value 变量的值。 from reactpy import component, hooks, html, runcomponent
def SyncedInputs():value, set_value hooks.use_state()return html.p(Input(First input, value, set_value),Input(Second input, value, set_value),)component
def Input(label, value, set_value):def handle_change(event):set_value(event[target][value])return html.label(label , html.input({value: value, on_change: handle_change}))run(SyncedInputs) 执行脚本后在 First input 中输入的字符同时也会出现在 Second input 中。 下面是一个点击事件处理的示例 from reactpy import component, html, runcomponent
def PrintButton(display_text, message_text):def handle_event(event):print(message_text)return html.button({on_click: handle_event}, display_text)component
def App():return html.div(PrintButton(Play, Playing),PrintButton(Pause, Paused),)run(App) 当点击 Play 时终端将打印 Playing点击 Pause 按钮将打印 Paused 最后再看一个示例在页面中显示图片 from reactpy import component, html, runcomponent
def Title(title):return html.h1(title)# 使用网站的logo图片
# 设置CSS样式width: 30%
component
def Photo():return html.img({src: https://xugaoxiang.com/wp-content/uploads/2020/05/logo.png,style: {width: 30%},})component
def PhotoViewer():return html.section(Title(My logo.),Photo())run(PhotoViewer) 代码运行后效果是这样的 4 总结 ReactPy 是一个 Python 库它为使用 Python 进行前端开发带来了类似 ReactJS 的功能。借助 ReactPy您可以轻松成为全栈开发人员使用相同的语言处理前端和后端。