跳转到内容

gpui-component

通过 GPUI Kit 的 gpui::component 模块使用原生控件,可确保应用代码与组件库始终共享同一份 GPUI 引擎实例。你可以运行可运行示例中的 component 程序,直接体验 Button、Input 与 Popover。

将 gpui-kit 重命名为 gpui:

Cargo.toml
[dependencies]
gpui = { package = "gpui-kit", version = "=0.10.0" }
gpui-rsx = "0.13.0"

GPUI Kit 通过 gpui::component 导出带样式的控件,通过 gpui::base 导出无样式基础行为,并通过 gpui::assets 提供图标资源。打开窗口前请调用 gpui::init(cx),并使用 gpui::open_window(...) 挂载根视图。

2. 构造控件:<Tag(...)> 与 base={...}

Section titled “2. 构造控件:<Tag(...)> 与 base={...}”

对于通过 Type::new(...) 构造的组件,可以直接在标签名后的括号内传参:

use gpui::component::button::{Button, ButtonVariants as _};
use gpui::component::Sizable as _;
rsx! {
<Button("save")
label="保存"
small
primary
/>
}
// 编译期展开为:
// Button::new("save").label("保存").small().primary()
  • 大写路径会展开为 Type::new(...)(例如 <Button("save") /> → Button::new("save"),<Tab() /> → Tab::new())。
  • 小写路径会直接调用同名工厂函数(<widget("a") /> → widget("a"))。

使用 base={...} 传入预配置构造器

Section titled “使用 base={...} 传入预配置构造器”

当你手里已有构造好的 builder,或需要调用与 GPUI 有状态属性重名的组件方法时,请使用宏专用的 base 属性:

// Tab::aria_label 是组件自身方法,写成属性会被识别为 GPUI 的有状态 aria_label
rsx! {
<Tab
base={Tab::new().label("概览").aria_label("概览标签页")}
underline
/>
}

gpui-component 的许多样式与变体方法(如 .primary()、.small())定义在扩展 trait 上。在视图模块顶部显式导入它们,能让编译错误更直观:

use gpui::component::button::{Button, ButtonVariants as _};
use gpui::component::Sizable as _;

如果编译器报组件与应用之间的 GPUI 类型不匹配,优先排查是否存在多个 gpui-pre 实例:

终端窗口
cargo check --manifest-path demo/Cargo.toml --bins --locked
cargo xtask check-gpui
cargo tree --manifest-path demo/Cargo.toml --locked -i gpui-pre

请提交应用的 Cargo.lock,确保团队解析出完全一致的 Kit 依赖图。