R

ReflexKR

Reflex 官方文档

组件工坊:Reflex 组件库 100 例

·

课程概览

布局

·

Box

·

Flex

·

Stack

·

Grid

·

Container

·

Section

·

Center

·

Spacer

·

Separator

·

Card

·

Inset

·

Aspect Ratio

·

Fragment

排版

·

Text

·

Heading

·

Link

·

Code

·

Markdown

·

Blockquote

·

Quote

·

Strong

·

Em

·

Kbd

表单

·

Button

·

Input

·

Text Area

·

Checkbox

·

Switch

·

Radio Group

·

Select

·

Slider

·

Form

·

Upload

数据展示

·

Badge

·

Avatar

·

Icon

·

Callout

·

List

·

Data List

·

Code Block

·

Progress

·

Spinner

·

Scroll Area

·

Moment

展开与切换

·

Tabs

·

Accordion

·

Segmented Control

浮层

·

Tooltip

·

Popover

·

Hover Card

·

Dialog

·

Alert Dialog

·

Drawer

·

Dropdown Menu

·

Context Menu

·

Toast

动态渲染

·

Cond

·

Match

·

Foreach

·

Auto Scroll

媒体

·

Image

·

Audio

·

Video

表格与数据网格

·

Table

·

Data Table

·

Data Editor

图表

·

Area Chart

·

Bar Chart

·

Line Chart

·

Composed Chart

·

Pie Chart

·

Radar Chart

·

Radial Bar Chart

·

Scatter Chart

·

Funnel Chart

·

Treemap

·

Sankey Chart

·

Error Bar

图表部件

·

Axis

·

Cartesian Grid

·

Chart Tooltip

·

Legend

·

Label

·

Reference

·

Brush

其他图表库

·

Plotly

·

Pyplot

HTML 元素

·

HTML

·

HTML Text

·

HTML Layout

·

HTML Forms

·

HTML Media

·

HTML Tables

·

SVG

其他工具

·

Theme

·

Skeleton

·

Clipboard

·

Html Embed

·

Script

·

Memo

组件工坊:Reflex 组件库 100 例
动态渲染

Cond

工坊订单

请在商城页头放一个登录按钮。登录之后,那个位置要显示用户名和退出按钮。

rx.cond(条件, A, B) 在条件为真时显示 A,为假时显示 B。条件里通常放 State 的值。Python 的 if 只在构建页面时执行一次,无法根据 State 的值切换界面。想在浏览器里每次值变化时重新选择,就用 rx.cond。

Text 1

class CondBasicState(rx.State):
    show: bool = True

    @rx.event
    def change(self):
        self.show = not self.show


rx.vstack(
    rx.button("Toggle", on_click=CondBasicState.change),
    rx.cond(
        CondBasicState.show,
        rx.text("Text 1", color="blue"),
        rx.text("Text 2", color="red"),
    ),
)

改改条件

rx.cond 没有外观属性,那就直接切换条件试试。像第二行那样给两个非组件的值(这里是颜色名),rx.cond 就会变成一个选择值而不是组件的 Var,可以放到属性的位置上。

试着改属性

Text 1

Status

show

ok

rx.hstack(
    rx.cond(
        True,
        rx.text("Text 1", color="blue"),
        rx.text("Text 2", color="red"),
    ),
    rx.badge(
        "Status",
        color_scheme=rx.cond(True, "green", "red"),
    ),
    spacing="4",
    align="center",
)
show 决定显示哪段文字,ok 决定徽章的 color_scheme。实际应用中这里放的是 State 的值。
参数取值用途
第一个(cond)Var(通常是 bool)选择依据。空字符串·0·空列表等视为假
第二个组件或值为真时显示的内容
第三个组件或值为假时显示的内容。如果是组件可以省略

省略第二个组件

第三个参数可以省略,这样条件为假时什么都不显示。适合“有才显示”的场景。用作属性值(两个值)时不能省略。

This text appears when condition is True

This text is always visible

class CondOptionalState(rx.State):
    show_optional: bool = True

    @rx.event
    def toggle_optional(self):
        self.show_optional = not self.show_optional


rx.vstack(
    rx.button("Toggle", on_click=CondOptionalState.toggle_optional),
    rx.cond(
        CondOptionalState.show_optional,
        rx.text("This text appears when condition is True", color="green"),
    ),
    rx.text("This text is always visible", color="gray"),
)

取反:~

在 Var 前加 ~ 就会把条件反过来(相当于 Python 的 not)。Var 不能用 not,所以用 ~。下面两行总是相反地显示。

Text 1

Text 2

class CondBasicState(rx.State):
    show: bool = True

    @rx.event
    def change(self):
        self.show = not self.show


rx.vstack(
    rx.button("Toggle", on_click=CondBasicState.change),
    rx.cond(CondBasicState.show, rx.text("Text 1", color="blue"), rx.text("Text 2", color="red")),
    rx.cond(~CondBasicState.show, rx.text("Text 1", color="blue"), rx.text("Text 2", color="red")),
)

多个条件:& 与 |

Var 之间不用 and·or,而是用 &(并且)和 |(或者)连接。&·| 比 >= 先计算,所以比较式一定要加括号。下面的例子中,18 岁以上、65 岁以下可以工作;未满 13 岁或 65 岁以上会显示折扣徽章。

Age: 19

You can work!

import random


class CondComplexState(rx.State):
    age: int = 19

    @rx.event
    def change(self):
        self.age = random.randint(0, 100)


rx.vstack(
    rx.button("Random age", on_click=CondComplexState.change),
    rx.text(f"Age: {CondComplexState.age}"),
    rx.cond(
        (CondComplexState.age >= 18) & (CondComplexState.age <= 65),
        rx.text("You can work!", color="green"),
        rx.text("You cannot work!", color="red"),
    ),
    rx.cond(
        (CondComplexState.age < 13) | (CondComplexState.age >= 65),
        rx.badge("Discount ticket", color_scheme="orange"),
    ),
)

嵌套:if · elif · else

在 rx.cond 的第三个位置再放一个 rx.cond,就相当于 elif。下面区分正数·0·负数。

0 is Zero!

import random


class CondNestedState(rx.State):
    num: int = 0

    @rx.event
    def change(self):
        self.num = random.randint(-10, 10)


rx.vstack(
    rx.button("Random number", on_click=CondNestedState.change),
    rx.cond(
        CondNestedState.num > 0,
        rx.text(f"{CondNestedState.num} is Positive!", color="orange"),
        rx.cond(
            CondNestedState.num == 0,
            rx.text(f"{CondNestedState.num} is Zero!", color="blue"),
            rx.text(f"{CondNestedState.num} is Negative!", color="red"),
        ),
    ),
)

再看一个稍复杂的例子:这段 Python 代码找出三个数中最大的那个,如果有相等的数就提示出来。

a = 8
b = 10
c = 2

if (a > b and a > c) and (a != b and a != c):
    print(a, " is the largest!")
elif (b > a and b > c) and (b != a and b != c):
    print(b, " is the largest!")
elif (c > a and c > b) and (c != a and c != b):
    print(c, " is the largest!")
else:
    print("Some of the numbers are equal!")

把同样的逻辑改写成三层 rx.cond 就是这样。“最大”意味着比另外两个数都大,所以不用另外检查它们是否互不相同。点“打乱”看看出现相同数字时的情况。分支比这更多时,用 Match 更好读。

a=8 b=10 c=2

10 is the largest!

import random


class CondLargestState(rx.State):
    a: int = 8
    b: int = 10
    c: int = 2

    @rx.event
    def shuffle(self):
        self.a, self.b, self.c = (random.randint(1, 4) for _ in range(3))


rx.vstack(
    rx.hstack(
        rx.button("Shuffle", on_click=CondLargestState.shuffle),
        rx.code(f"a={CondLargestState.a} b={CondLargestState.b} c={CondLargestState.c}"),
        align="center",
    ),
    rx.cond(
        (CondLargestState.a > CondLargestState.b) & (CondLargestState.a > CondLargestState.c),
        rx.text(f"{CondLargestState.a} is the largest!"),
        rx.cond(
            (CondLargestState.b > CondLargestState.a) & (CondLargestState.b > CondLargestState.c),
            rx.text(f"{CondLargestState.b} is the largest!"),
            rx.cond(
                (CondLargestState.c > CondLargestState.a) & (CondLargestState.c > CondLargestState.b),
                rx.text(f"{CondLargestState.c} is the largest!"),
                rx.text("Some of the numbers are equal!"),
            ),
        ),
    ),
)

完成订单

只凭是否登录这一个值,就切换右侧整块区域。为真时显示头像·用户名·退出按钮这一组,为假时只显示一个登录按钮。

Shop

class CondLoginState(rx.State):
    logged_in: bool = False
    user: str = "Ada"

    @rx.event
    def log_in(self):
        self.logged_in = True

    @rx.event
    def log_out(self):
        self.logged_in = False


rx.hstack(
    rx.text("Shop", weight="bold"),
    rx.spacer(),
    rx.cond(
        CondLoginState.logged_in,
        rx.hstack(
            rx.avatar(fallback=CondLoginState.user[0], size="2", radius="full"),
            rx.text(CondLoginState.user, size="2"),
            rx.button("Log out", on_click=CondLoginState.log_out, size="1", variant="soft", color_scheme="gray"),
            align="center",
        ),
        rx.button("Log in", on_click=CondLoginState.log_in, size="2"),
    ),
    width="100%",
    max_width="420px",
    align="center",
    padding="10px 14px",
    border=f"1px solid {rx.color('gray', 6)}",
    border_radius="10px",
)

工坊笔记

  • rx.cond(条件, 为真时, 为假时)。Python 的 if 不能用于 State 的值。

  • 为假时的组件可以省略。给两个值就会成为可以放进属性的 Var。

  • 取反用 ~,并且·或者用 & · |。比较式一定要加括号。

  • elif 靠嵌套 rx.cond 实现。分支多时用 rx.match。

← 上一课

浮层 · Toast

下一课 →

动态渲染 · Match

订阅新课时和新课程通知

本课程新增课时或推出后续课程时,我们会发邮件通知你。

收集项目:电子邮箱 · 用途:本课程的新课时和上线通知 · 保存期限:直到你要求删除。不会用于其他用途,也不会提供给他人。回复任意通知邮件,我们会立即删除。

问答

关于本课有任何疑问都可以在这里留言。所有语言版本页面的提问会汇集在一起。

以纯文本显示,不支持链接和格式。

R

ReflexKR

动手学 Python 和 Reflex。所有示例均已在 Reflex 0.10.0 上实际运行验证。

ReflexKR 免费,没有横幅广告。如果对你有帮助,欢迎请我们喝杯咖啡。 ☕ 请我们喝杯咖啡

联盟链接与赞助说明
한국어English日本語简体中文EspañolDeutsch

© 2026 ReflexKR · Since 2026 · CC BY-NC 4.0

Built with Reflex