文档
命令
命令
快速、可组合、无样式的 React 命令菜单。
未找到结果。
日历
搜索表情符号
计算器
个人资料⌘P
账单⌘B
设置⌘S
关于
<Command />
组件使用了 cmdk
组件,由 pacocoursey 开发。
安装
pnpm dlx shadcn@latest add command
用法
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>
示例
对话框
按下 ⌘J
要在一个对话框中显示命令菜单,请使用 <CommandDialog />
组件。
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>
)
}
组合框
你可以将 <Command />
组件用作组合框。请参阅组合框页面以获取更多信息。
更新日志
2024-10-25 图标的类
为 <CommandItem />
添加了 gap-2 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0
,以自动设置内部图标的样式。
将以下类添加到你的 command.tsx
文件中的 cva
调用中。
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}
/>
))