Docs
命令
命令
快速、可组合、无样式的 React 命令菜单。
No results found.
Calendar
Search Emoji
Calculator
Profile⌘P
Billing⌘B
Settings⌘S
关于
<Command />
组件使用了 pacocoursey 的 cmdk
组件。
安装
pnpm dlx shadcn@latest add command
使用
import {
Command,
CommandDialog,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
CommandSeparator,
CommandShortcut,
} from "@/components/ui/command"
<Command>
<CommandInput placeholder="输入命令或搜索..." />
<CommandList>
<CommandEmpty>未找到结果。</CommandEmpty>
<CommandGroup heading="建议">
<CommandItem>日历</CommandItem>
<CommandItem>搜索表情符号</CommandItem>
<CommandItem>计算器</CommandItem>
</CommandGroup>
<CommandSeparator />
<CommandGroup heading="设置">
<CommandItem>个人资料</CommandItem>
<CommandItem>账单</CommandItem>
<CommandItem>设置</CommandItem>
</CommandGroup>
</CommandList>
</Command>
示例
对话框
Press ⌘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="输入命令或搜索..." />
<CommandList>
<CommandEmpty>未找到结果。</CommandEmpty>
<CommandGroup heading="建议">
<CommandItem>日历</CommandItem>
<CommandItem>搜索表情符号</CommandItem>
<CommandItem>计算器</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}
/>
))