Docs
命令

命令

用于 React 的快速、可组合、无样式命令菜单。

关于

¥About

<Command /> 组件使用 pacocourseycmdk 组件。

¥The <Command /> component uses the cmdk component by pacocoursey.

安装

¥Installation

pnpm dlx shadcn@latest add command

用法

¥Usage

import {
  Command,
  CommandDialog,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
  CommandSeparator,
  CommandShortcut,
} from "@/components/ui/command"
<Command>
  <CommandInput placeholder="Type a command or search..." />
  <CommandList>
    <CommandEmpty>No results found.</CommandEmpty>
    <CommandGroup heading="Suggestions">
      <CommandItem>Calendar</CommandItem>
      <CommandItem>Search Emoji</CommandItem>
      <CommandItem>Calculator</CommandItem>
    </CommandGroup>
    <CommandSeparator />
    <CommandGroup heading="Settings">
      <CommandItem>Profile</CommandItem>
      <CommandItem>Billing</CommandItem>
      <CommandItem>Settings</CommandItem>
    </CommandGroup>
  </CommandList>
</Command>

示例

¥Examples

对话框

¥Dialog

Press J

要在对话框中显示命令菜单,请使用 <CommandDialog /> 组件。

¥To show the command menu in a dialog, use the <CommandDialog /> component.

export function CommandMenu() {
  const [open, setOpen] = React.useState(false)
 
  React.useEffect(() => {
    const down = (e: KeyboardEvent) => {
      if (e.key === "k" && (e.metaKey || e.ctrlKey)) {
        e.preventDefault()
        setOpen((open) => !open)
      }
    }
    document.addEventListener("keydown", down)
    return () => document.removeEventListener("keydown", down)
  }, [])
 
  return (
    <CommandDialog open={open} onOpenChange={setOpen}>
      <CommandInput placeholder="Type a command or search..." />
      <CommandList>
        <CommandEmpty>No results found.</CommandEmpty>
        <CommandGroup heading="Suggestions">
          <CommandItem>Calendar</CommandItem>
          <CommandItem>Search Emoji</CommandItem>
          <CommandItem>Calculator</CommandItem>
        </CommandGroup>
      </CommandList>
    </CommandDialog>
  )
}

组合框

¥Combobox

你可以将 <Command /> 组件用作组合框。有关更多信息,请参阅 组合框 页面。

¥You can use the <Command /> component as a combobox. See the Combobox page for more information.

更新日志

¥Changelog

2024-10-25 图标的类

¥2024-10-25 Classes for icons

gap-2 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0 添加到 <CommandItem /> 以自动设置内部图标样式。

¥Added gap-2 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0 to the <CommandItem /> to automatically style icon inside.

将以下类添加到你的 command.tsx 文件中的 cva 调用。

¥Add the following classes to the cva call in your command.tsx file.

command.tsx
const CommandItem = React.forwardRef<
  React.ElementRef<typeof CommandPrimitive.Item>,
  React.ComponentPropsWithoutRef<typeof CommandPrimitive.Item>
>(({ className, ...props }, ref) => (
  <CommandPrimitive.Item
    ref={ref}
    className={cn(
      "... gap-2 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
      className
    )}
    {...props}
  />
))