Command.tsx

Command.tsx

基本信息

  • 类型: React 组件 (shadcn/ui)
  • 路径: ./src/components/ui/command.tsx

功能描述

命令面板组件,用于快速搜索和执行命令。基于 cmdk 库,支持对话框模式、分组、快捷键提示等功能。

导出内容

  • Command - 命令面板根组件
  • CommandDialog - 对话框模式的命令面板
  • CommandInput - 搜索输入框
  • CommandList - 命令列表容器
  • CommandEmpty - 空结果提示
  • CommandGroup - 命令分组
  • CommandItem - 单个命令项
  • CommandShortcut - 快捷键提示
  • CommandSeparator - 分隔线

Props 接口

Command

属性类型必填默认值说明
classNamestring-自定义CSS类名
...propsReact.ComponentProps<typeof CommandPrimitive>-cmdk 属性

CommandDialog

属性类型必填默认值说明
titlestring'Command Palette'对话框标题
descriptionstring'Search for a command to run...'对话框描述
classNamestring-自定义CSS类名
showCloseButtonbooleantrue是否显示关闭按钮
...propsReact.ComponentProps<typeof Dialog>-对话框属性

CommandItem

属性类型必填默认值说明
classNamestring-自定义CSS类名
...propsReact.ComponentProps<typeof CommandPrimitive.Item>-cmdk Item 属性

依赖

  • cmdk - 命令面板库
  • lucide-react - 图标库 (SearchIcon)
  • @/lib/utils - 工具函数 (cn)
  • @/components/ui/dialog - 对话框组件

使用示例

import {
  Command,
  CommandDialog,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
  CommandSeparator,
  CommandShortcut,
} from "@/components/ui/command";
import { useState } from "react";

// 基础命令面板
<Command>
  <CommandInput placeholder="搜索命令..." />
  <CommandList>
    <CommandEmpty>未找到结果</CommandEmpty>
    <CommandGroup heading="建议">
      <CommandItem>
        <Calendar className="mr-2 size-4" />
        <span>日历</span>
      </CommandItem>
      <CommandItem>
        < Smile className="mr-2 size-4" />
        <span>表情</span>
        <CommandShortcut>⌘E</CommandShortcut>
      </CommandItem>
    </CommandGroup>
    <CommandSeparator />
    <CommandGroup heading="设置">
      <CommandItem>个人资料</CommandItem>
      <CommandItem>账户设置</CommandItem>
    </CommandGroup>
  </CommandList>
</Command>

// 对话框模式
const [open, setOpen] = useState(false);
<CommandDialog open={open} onOpenChange={setOpen}>
  <CommandInput placeholder="输入命令..." />
  <CommandList>
    {/* ... */}
  </CommandList>
</CommandDialog>
← 返回目录