Components
@shadcn/react
@shadcn/helpers
Utilities
"use client"
import * as React from "react"安装#
pnpm dlx shadcn@latest add button-group
使用方法#
import {
ButtonGroup,
ButtonGroupSeparator,
ButtonGroupText,
} from "@/components/ui/button-group"<ButtonGroup>
<Button>按钮 1</Button>
<Button>按钮 2</Button>
</ButtonGroup>组合#
使用以下组合来构建 ButtonGroup:
ButtonGroup
├── 按钮或输入框
├── ButtonGroupSeparator
└── ButtonGroupText可访问性#
ButtonGroup组件的role属性被设置为group。- 使用 Tab 键在组内按钮间切换。
- 使用
aria-label或aria-labelledby为按钮组添加标签。
<ButtonGroup aria-label="按钮组">
<Button>按钮 1</Button>
<Button>按钮 2</Button>
</ButtonGroup>ButtonGroup 和 ToggleGroup 的区别#
- 当你想将执行动作的按钮进行分组时,使用
ButtonGroup组件。 - 当你想将切换状态的按钮分组时,使用
ToggleGroup组件。
方向#
通过设置 orientation 属性改变按钮组布局。
import { MinusIcon, PlusIcon } from "lucide-react"
import { Button } from "@/components/ui/button"大小#
通过单个按钮上的 size 属性控制按钮大小。
import { PlusIcon } from "lucide-react"
import { Button } from "@/components/ui/button"嵌套#
嵌套 <ButtonGroup> 组件以创建带间距的按钮组。
import { AudioLinesIcon, PlusIcon } from "lucide-react"
import { Button } from "@/components/ui/button"分隔符#
ButtonGroupSeparator 组件在组内按钮之间进行视觉分割。
当按钮变体为 outline 时不需要分隔符,因为它们有边框。对于其他变体,推荐使用分隔符以增强视觉层次。
import { Button } from "@/components/ui/button"
import {
ButtonGroup,分割#
通过两个按钮间添加 ButtonGroupSeparator 创建分割按钮组。
import { IconPlus } from "@tabler/icons-react"
import { Button } from "@/components/ui/button"输入#
将 Input 组件包裹在按钮组内。
import { SearchIcon } from "lucide-react"
import { Button } from "@/components/ui/button"输入组#
包裹 InputGroup 组件以创建复杂的输入布局。
"use client"
import * as React from "react"下拉菜单#
创建带有 DropdownMenu 组件的分割按钮组。
"use client"
import {Select#
与 Select 组件配合使用。
"use client"
import * as React from "react"弹出框#
与 Popover 组件一起使用。
import { BotIcon, ChevronDownIcon } from "lucide-react"
import { Button } from "@/components/ui/button"RTL#
要在 shadcn/ui 中启用 RTL 支持,请参阅 RTL 配置指南。
"use client"
import * as React from "react"API 参考#
ButtonGroup#
ButtonGroup 组件是一个容器,将相关按钮以统一样式分组。
| 属性 | 类型 | 默认值 |
|---|---|---|
orientation | "horizontal" | "vertical" | "horizontal" |
<ButtonGroup>
<Button>按钮 1</Button>
<Button>按钮 2</Button>
</ButtonGroup>嵌套多个按钮组可创建带间距的复杂布局。详见 嵌套 示例。
<ButtonGroup>
<ButtonGroup />
<ButtonGroup />
</ButtonGroup>ButtonGroupSeparator#
ButtonGroupSeparator 组件在组内按钮之间做视觉分割。
| 属性 | 类型 | 默认值 |
|---|---|---|
orientation | "horizontal" | "vertical" | "vertical" |
<ButtonGroup>
<Button>按钮 1</Button>
<ButtonGroupSeparator />
<Button>按钮 2</Button>
</ButtonGroup>ButtonGroupText#
使用该组件在按钮组内显示文本。
| 属性 | 类型 | 默认值 |
|---|---|---|
asChild | boolean | false |
<ButtonGroup>
<ButtonGroupText>文本</ButtonGroupText>
<Button>按钮</Button>
</ButtonGroup>使用 asChild 属性以自定义组件作为文本,例如标签。
import { ButtonGroupText } from "@/components/ui/button-group"
import { Label } from "@/components/ui/label"
export function ButtonGroupTextDemo() {
return (
<ButtonGroup>
<ButtonGroupText asChild>
<Label htmlFor="name">文本</Label>
</ButtonGroupText>
<Input placeholder="请输入内容..." id="name" />
</ButtonGroup>
)
}