重要前提
安装AI Skills的关键前提是:必须科学上网,且开启TUN模式,这一点至关重要,直接决定安装能否顺利完成,在此郑重提醒三遍:科学上网,科学上网,科学上网。查看完整安装教程 →
reflex-dev by silvainfm/claude-skills
npx skills add https://github.com/silvainfm/claude-skills --skill reflex-devReflex 是一个全栈 Python 框架,用于构建无需编写 JavaScript 的 Web 应用程序。应用会被编译为 React 前端和 FastAPI 后端,状态管理和事件处理程序完全在 Python 中运行。
架构:
状态是一个 Python 类,它保存所有可变数据和事件处理程序。所有状态变量必须是 JSON 可序列化的。
import reflex as rx
class AppState(rx.State):
# 状态变量(任何 JSON 可序列化类型)
count: int = 0
items: list[str] = []
user_name: str = ""
# 事件处理程序 - 修改状态的唯一方式
def increment(self):
self.count += 1
def add_item(self, item: str):
self.items.append(item)
# 计算变量(派生状态)
@rx.var
def item_count(self) -> int:
return len(self.items)
关键规则:
@rx.var 装饰器处理计算值/派生值广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
组件是 UI 构建块。Reflex 提供了 60 多个内置组件。
import reflex as rx
def header() -> rx.Component:
return rx.heading("My App", size="lg")
def counter_component(state: AppState) -> rx.Component:
return rx.vstack(
rx.text(f"Count: {state.count}"),
rx.button("Increment", on_click=state.increment),
spacing="4"
)
常用组件:
rx.vstack, rx.hstack, rx.box, rx.containerrx.heading, rx.text, rx.coderx.input, rx.text_area, rx.select, rx.checkboxrx.button, rx.link, rx.icon_buttonrx.table, rx.data_table, rx.listrx.recharts.line_chart, rx.recharts.bar_chart 等事件处理程序响应用户交互,并且是修改状态的唯一方式。
class FormState(rx.State):
form_data: dict[str, str] = {}
# 简单事件处理程序
def handle_submit(self):
print(f"Submitted: {self.form_data}")
# 带参数的事件处理程序
def update_field(self, field: str, value: str):
self.form_data[field] = value
# 异步事件处理程序(用于 API 调用、数据库查询)
async def fetch_data(self):
# 可以使用任何 Python 库
import httpx
async with httpx.AsyncClient() as client:
response = await client.get("https://api.example.com/data")
self.data = response.json()
事件触发器(将组件连接到处理程序):
on_click:按钮点击on_change:输入字段变化on_submit:表单提交on_mount:组件首次渲染on_blur, on_focus:输入焦点事件标准 Reflex 应用结构:
my_app/
├── my_app/
│ ├── __init__.py # 空文件
│ └── my_app.py # 主应用文件(状态 + 页面)
├── assets/ # 静态文件(图片、字体等)
├── .web/ # 自动生成的前端代码(请勿编辑)
├── rxconfig.py # Reflex 配置
└── requirements.txt # Python 依赖项
import reflex as rx
# 1. 定义状态
class State(rx.State):
count: int = 0
def increment(self):
self.count += 1
# 2. 定义页面
def index() -> rx.Component:
return rx.container(
rx.heading("Welcome"),
rx.button("Click", on_click=State.increment),
rx.text(f"Count: {State.count}")
)
def about() -> rx.Component:
return rx.container(
rx.heading("About"),
rx.link("Home", href="/")
)
# 3. 创建应用并添加路由
app = rx.App()
app.add_page(index, route="/")
app.add_page(about, route="/about")
class FormState(rx.State):
name: str = ""
email: str = ""
def handle_submit(self, form_data: dict):
self.name = form_data.get("name", "")
self.email = form_data.get("email", "")
def form_page():
return rx.form(
rx.vstack(
rx.input(name="name", placeholder="Name"),
rx.input(name="email", placeholder="Email"),
rx.button("Submit", type="submit"),
),
on_submit=FormState.handle_submit,
)
class DataState(rx.State):
data: list[dict] = [
{"id": 1, "name": "Alice", "age": 25},
{"id": 2, "name": "Bob", "age": 30},
]
def data_table_page():
return rx.data_table(
data=DataState.data,
columns=["id", "name", "age"],
sort=True,
search=True,
pagination=True,
)
class UploadState(rx.State):
async def handle_upload(self, files: list[rx.UploadFile]):
for file in files:
upload_data = await file.read()
# 处理文件数据
outfile = f"./uploads/{file.filename}"
with open(outfile, "wb") as f:
f.write(upload_data)
def upload_page():
return rx.vstack(
rx.upload(
rx.button("Select Files"),
id="upload1",
),
rx.button(
"Upload",
on_click=UploadState.handle_upload(rx.upload_files(upload_id="upload1"))
),
)
import duckdb
import polars as pl
class DBState(rx.State):
records: list[dict] = []
async def load_data(self):
# 使用现有的数据库连接
conn = duckdb.connect("data/mydb.duckdb")
df = conn.execute("SELECT * FROM mytable").pl()
self.records = df.to_dicts()
conn.close()
async def insert_record(self, data: dict):
conn = duckdb.connect("data/mydb.duckdb")
conn.execute(
"INSERT INTO mytable (name, value) VALUES (?, ?)",
[data["name"], data["value"]]
)
conn.close()
await self.load_data() # 刷新数据
rx.box(
rx.text("Styled text"),
bg="#1a5f9e",
color="white",
padding="4",
border_radius="md",
)
rx.container(
rx.responsive_grid(
rx.box("Item 1", bg="blue"),
rx.box("Item 2", bg="green"),
rx.box("Item 3", bg="red"),
columns=[1, 2, 3], # 移动端 1 列,平板 2 列,桌面端 3 列
spacing="4",
),
max_width="1200px",
)
width, height, padding, margin, displaybg(背景), color(文本)font_size, font_weight, text_alignborder, border_radius, border_colorspacing(用于堆叠布局), gapapp = rx.App()
# 带参数的路由
@rx.page(route="/user/[id]")
def user_page() -> rx.Component:
return rx.text(f"User ID: {State.router.page.params.get('id')}")
# 简单路由
app.add_page(index, route="/")
app.add_page(about, route="/about")
# 链接
rx.link("Go to About", href="/about")
# 编程式导航
def go_home(self):
return rx.redirect("/")
pip install reflex
reflex init
reflex run
应用运行在 http://localhost:3000 并支持自动重载。
reflex run # 启动开发服务器
reflex export # 构建生产环境包
reflex db init # 初始化数据库(如果使用 Reflex DB)
reflex db migrate # 运行数据库迁移
状态组织:将大型状态拆分为子状态
class AuthState(rx.State):
user: str = ""
class DataState(rx.State):
items: list = []
组件可重用性:创建可重用的组件函数
def card(title: str, content: str) -> rx.Component:
return rx.box(
rx.heading(title, size="md"),
rx.text(content),
padding="4",
border="1px solid #ddd",
)
事件处理程序性能:对 I/O 操作使用异步
async def fetch_data(self):
# 异步 I/O 不会阻塞其他用户
self.data = await some_api_call()
类型提示:始终为状态变量和事件处理程序添加类型提示
count: int = 0
items: list[str] = []
def update_count(self, value: int) -> None:
self.count = value
查看 examples/ 目录获取完整的工作示例:
查看 references/patterns.md 获取详细示例:
每周安装量
63
代码仓库
GitHub 星标数
2
首次出现
2026年1月23日
安全审计
安装于
opencode56
gemini-cli50
codex49
github-copilot47
amp43
kimi-cli41
Reflex is a full-stack Python framework for building web applications without writing JavaScript. Apps compile to a React frontend and FastAPI backend, with state management and event handlers running entirely in Python.
Architecture:
State is a Python class that holds all mutable data and event handlers. All state variables must be JSON-serializable.
import reflex as rx
class AppState(rx.State):
# State variables (any JSON-serializable type)
count: int = 0
items: list[str] = []
user_name: str = ""
# Event handlers - the ONLY way to modify state
def increment(self):
self.count += 1
def add_item(self, item: str):
self.items.append(item)
# Computed vars (derived state)
@rx.var
def item_count(self) -> int:
return len(self.items)
Key Rules:
@rx.var decorator for computed/derived valuesComponents are UI building blocks. Reflex provides 60+ built-in components.
import reflex as rx
def header() -> rx.Component:
return rx.heading("My App", size="lg")
def counter_component(state: AppState) -> rx.Component:
return rx.vstack(
rx.text(f"Count: {state.count}"),
rx.button("Increment", on_click=state.increment),
spacing="4"
)
Common Components:
rx.vstack, rx.hstack, rx.box, rx.containerrx.heading, rx.text, rx.coderx.input, rx.text_area, rx.select, rx.checkboxEvent handlers respond to user interactions and are the ONLY way to modify state.
class FormState(rx.State):
form_data: dict[str, str] = {}
# Simple event handler
def handle_submit(self):
print(f"Submitted: {self.form_data}")
# Event handler with argument
def update_field(self, field: str, value: str):
self.form_data[field] = value
# Async event handler (for API calls, DB queries)
async def fetch_data(self):
# Can use any Python library
import httpx
async with httpx.AsyncClient() as client:
response = await client.get("https://api.example.com/data")
self.data = response.json()
Event Triggers (connect components to handlers):
on_click: Button clickson_change: Input field changeson_submit: Form submissionson_mount: Component first renderson_blur, on_focus: Input focus eventsStandard Reflex app structure:
my_app/
├── my_app/
│ ├── __init__.py # Empty
│ └── my_app.py # Main app file (State + pages)
├── assets/ # Static files (images, fonts, etc.)
├── .web/ # Auto-generated frontend (don't edit)
├── rxconfig.py # Reflex configuration
└── requirements.txt # Python dependencies
import reflex as rx
# 1. Define State
class State(rx.State):
count: int = 0
def increment(self):
self.count += 1
# 2. Define Pages
def index() -> rx.Component:
return rx.container(
rx.heading("Welcome"),
rx.button("Click", on_click=State.increment),
rx.text(f"Count: {State.count}")
)
def about() -> rx.Component:
return rx.container(
rx.heading("About"),
rx.link("Home", href="/")
)
# 3. Create App and Add Routes
app = rx.App()
app.add_page(index, route="/")
app.add_page(about, route="/about")
class FormState(rx.State):
name: str = ""
email: str = ""
def handle_submit(self, form_data: dict):
self.name = form_data.get("name", "")
self.email = form_data.get("email", "")
def form_page():
return rx.form(
rx.vstack(
rx.input(name="name", placeholder="Name"),
rx.input(name="email", placeholder="Email"),
rx.button("Submit", type="submit"),
),
on_submit=FormState.handle_submit,
)
class DataState(rx.State):
data: list[dict] = [
{"id": 1, "name": "Alice", "age": 25},
{"id": 2, "name": "Bob", "age": 30},
]
def data_table_page():
return rx.data_table(
data=DataState.data,
columns=["id", "name", "age"],
sort=True,
search=True,
pagination=True,
)
class UploadState(rx.State):
async def handle_upload(self, files: list[rx.UploadFile]):
for file in files:
upload_data = await file.read()
# Process file data
outfile = f"./uploads/{file.filename}"
with open(outfile, "wb") as f:
f.write(upload_data)
def upload_page():
return rx.vstack(
rx.upload(
rx.button("Select Files"),
id="upload1",
),
rx.button(
"Upload",
on_click=UploadState.handle_upload(rx.upload_files(upload_id="upload1"))
),
)
import duckdb
import polars as pl
class DBState(rx.State):
records: list[dict] = []
async def load_data(self):
# Use existing database connection
conn = duckdb.connect("data/mydb.duckdb")
df = conn.execute("SELECT * FROM mytable").pl()
self.records = df.to_dicts()
conn.close()
async def insert_record(self, data: dict):
conn = duckdb.connect("data/mydb.duckdb")
conn.execute(
"INSERT INTO mytable (name, value) VALUES (?, ?)",
[data["name"], data["value"]]
)
conn.close()
await self.load_data() # Refresh
rx.box(
rx.text("Styled text"),
bg="#1a5f9e",
color="white",
padding="4",
border_radius="md",
)
rx.container(
rx.responsive_grid(
rx.box("Item 1", bg="blue"),
rx.box("Item 2", bg="green"),
rx.box("Item 3", bg="red"),
columns=[1, 2, 3], # 1 col mobile, 2 tablet, 3 desktop
spacing="4",
),
max_width="1200px",
)
width, height, padding, margin, displaybg (background), color (text)font_size, font_weight, text_alignborder, , app = rx.App()
# Route with parameters
@rx.page(route="/user/[id]")
def user_page() -> rx.Component:
return rx.text(f"User ID: {State.router.page.params.get('id')}")
# Simple routes
app.add_page(index, route="/")
app.add_page(about, route="/about")
# Links
rx.link("Go to About", href="/about")
# Programmatic navigation
def go_home(self):
return rx.redirect("/")
pip install reflex
reflex init
reflex run
App runs on http://localhost:3000 with auto-reload.
reflex run # Start dev server
reflex export # Build production bundle
reflex db init # Initialize database (if using Reflex DB)
reflex db migrate # Run migrations
State Organization : Split large states into substates
class AuthState(rx.State):
user: str = ""
class DataState(rx.State):
items: list = []
Component Reusability : Create reusable component functions
def card(title: str, content: str) -> rx.Component:
return rx.box(
rx.heading(title, size="md"),
rx.text(content),
padding="4",
border="1px solid #ddd",
)
Event Handler Performance : Use async for I/O operations
async def fetch_data(self):
# Async I/O won't block other users
self.data = await some_api_call()
Type Hints : Always type-hint state vars and event handlers
count: int = 0
items: list[str] = []
def update_count(self, value: int) -> None:
self.count = value
See examples/ directory for complete working examples:
See references/patterns.md for detailed examples of:
Weekly Installs
63
Repository
GitHub Stars
2
First Seen
Jan 23, 2026
Security Audits
Gen Agent Trust HubFailSocketPassSnykWarn
Installed on
opencode56
gemini-cli50
codex49
github-copilot47
amp43
kimi-cli41
agent-browser 浏览器自动化工具 - Vercel Labs 命令行网页操作与测试
169,700 周安装
shadcn/ui 设置工具:一键配置 Tailwind CSS v4 与 shadcn/ui 集成
89 周安装
Cursor子代理创建器:AI代理开发与多步骤工作流自动化专家指南
90 周安装
YouTube Data API v3 使用指南:搜索视频、获取详情、频道信息和评论
89 周安装
.NET跨平台UI开发指南:Blazor、MAUI、Uno、WPF、WinUI、WinForms全栈教程
90 周安装
销售负责人技能指南:B2B销售战略、团队建设与管道管理全解析
91 周安装
SQLAlchemy 代码审查指南:会话管理、N+1查询优化、Alembic迁移最佳实践
91 周安装
rx.buttonrx.linkrx.icon_buttonrx.table, rx.data_table, rx.listrx.recharts.line_chart, rx.recharts.bar_chart, etc.border_radiusborder_colorspacing (for stacks), gap