跳到主要内容

Base

文档:https://reflex.dev/docs/

Custom Components:https://reflex.dev/docs/custom-components/

# 初始化项目
reflex init
# 运行
reflex run

Reflex will hot reload any code changes in real time

import reflex as rx

术语

Components 组件:构建应用程序用户界面(UI)的基础元素

def round_button():
return rx.button(
rx.text("This is a page"),
border_radius=",15px", font_size="18px"
)
  • Children:嵌套在组件内的文本或其他 Reflex 组件;作为 positional arguments 传递
  • Props:影响组件行为和外观的属性;作为 keyword arguments 传递。

States 状态:在应用程序中,需要存储和显示变量。rx.State 类用于存储在应用运行时可以变化的变量,以及可以改变这些变量的函数。

class MyState(rx.State):
count: int = 0
color: str = "red"

要在组件中引用一个 State,可以将其作为 child 或 prop 传递。当状态变化时,组件会自动更新。

变量通过状态类中的类属性进行引用。例如,要在组件中引用 count 变量,可以使用 MyState.count。

def counter():
return rx.hstack(
# The heading `color` prop is set to the `color` var in MyState.
rx.heading("Count: ", color=MyState.color),
# The `count` var in `MyState` is passed as a child to the heading component.
rx.heading(MyState.count),
)

event_handlers 事件处理器:所有 State 的变化都是通过 State 类中的函数来处理的,这些函数称为 event_handlers

class CounterState2(rx.State):
count: int = 0

@rx.event
def increment(self, amount: int):
self.count += amount


def counter_variable():
return rx.hstack(
rx.heading(CounterState2.count),
rx.button(
"Increment by 1",
on_click=lambda: CounterState2.increment(1),
),
rx.button(
"Increment by 5",
on_click=lambda: CounterState2.increment(5),
),
)