# 切换按钮 · ToggleButton

- 页面: https://jiguang132.com/zh/resources/astryx/docs/toggle-button
- 资源: Astryx (https://jiguang132.com/zh/resources/astryx.md)
- 全部指南: https://jiguang132.com/zh/resources/astryx/docs.md

表示可以开启或关闭的操作状态。

## 安装与前置条件

```bash
npm install @astryxdesign/core@0.7.1 @astryxdesign/theme-neutral@0.7.1 @stylexjs/stylex@0.19.0
```

需要 React 19+，按顺序导入基础 CSS 和主题，并设置 Theme Provider。参见[开始使用](/resources/astryx/docs/getting-started)。

## 示例与使用方式

- **切换按钮 · 综合展示 / 分组 1**：首先体验这个示例，再查看代码理解组件的组合方式。
- **切换按钮 · 综合展示 2**：可交互查看这一用法的行为，复制代码时保留它实际使用的属性与导入。
- **切换按钮 · 交互示例 3**：可交互查看这一用法的行为，复制代码时保留它实际使用的属性与导入。
- **切换按钮 · 分组 4**：可交互查看这一用法的行为，复制代码时保留它实际使用的属性与导入。
- **切换按钮 · 分组 5**：可交互查看这一用法的行为，复制代码时保留它实际使用的属性与导入。
- **切换按钮 · 交互示例 6**：可交互查看这一用法的行为，复制代码时保留它实际使用的属性与导入。
- **切换按钮 · 交互示例 7**：可交互查看这一用法的行为，复制代码时保留它实际使用的属性与导入。
- **切换按钮 · 多种状态 8**：可交互查看这一用法的行为，复制代码时保留它实际使用的属性与导入。

## API 与上游详细参考

优先使用 0.7.1 官方中文说明；上游尚未提供中文的条目保留英文。属性名、类型及默认值保持原生 API，不把示例状态名称当成组件属性。

## Toggle Button

ToggleButton switches between selected and unselected states to represent a persistent on/off choice. Use it standalone for binary actions like bold, mute, or favorite, or inside a ToggleButtonGroup for single-select or multi-select toolbar controls.

| 属性 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| label * | string |  | Accessible label for the button. Used as visible text, or as aria-label for icon-only buttons. |
| isPressed | boolean |  | Whether the button is currently pressed. Ignored for a ToggleButtonGroup member with a value. |
| onPressedChange | (isPressed: boolean, event: MouseEvent) => void |  | Called synchronously when pressed state should change. Receives the next state and the click event; call event.preventDefault() to skip pressedChangeAction. Without an Action, the callback produces no Action-pending feedback. Ignored for a ToggleButtonGroup member with a value. |
| pressedChangeAction | (isPressed: boolean) => void \| Promise<void> |  | Action handler for API- or navigation-backed toggles, run in a transition after the synchronous onPressedChange callback unless that callback calls event.preventDefault(). Works without onPressedChange. Shows an optimistic pressed state and a spinner while pending, and remains interruptible by re-clicks. Omit it for callback-only toggles with no Action-pending feedback. Ignored for a ToggleButtonGroup member with a value. |
| size | 'sm' \| 'md' \| 'lg' | 'md' | Button size. Defaults to group size when inside a group. |
| elevation | 'none' \| 'low' \| 'med' \| 'high' | 'none' | Resting shadow depth for floating (FAB-style) toggle buttons, mirroring Button. `none` is the default flat button; `low`/`med`/`high` map to the shadow token scale. Applies inside a ToggleButtonGroup as well — grouped children retain their own elevation. |
| isDisabled | boolean | false | Whether the button is disabled. |
| isLoading | boolean | false | Whether the button shows a loading spinner. |
| icon | ReactNode |  | Icon element. When provided without children, button becomes icon-only with tooltip from label. |
| isIconOnly | boolean | false | When true, renders as a square icon-only button with `label` as the aria-label and an automatic tooltip from the label. |
| pressedIcon | ReactNode |  | Icon shown when pressed. Falls back to icon if not provided. |
| children | ReactNode |  | Visible content. If omitted with icon, button becomes icon-only. |
| tooltip | string |  | Tooltip text shown on hover. |
| value | string |  | Value identifier when used inside ToggleButtonGroup. Required in groups. |
| data-testid | string |  | Test selector for automated testing frameworks. |

### 使用建议

- Use a filled or colored icon for the pressed state so users can see the current state at a glance: an outline star vs a solid star, for example.
- Keep the label identical between pressed and unpressed states. Let the visual treatment (icon, weight, background) communicate the change.
- Wrap related toggles in a ToggleButtonGroup with an accessible label so screen readers announce them as a connected set.
- 避免：Don't use a ToggleButton for one-time actions like "Submit" or "Delete"; those are regular Buttons, not toggles.
- 避免：Don't mix ToggleButtons with regular Buttons inside the same group; use only ToggleButtons in a ToggleButtonGroup.
- 避免：Don't use a ToggleButton for on/off settings that persist across sessions; use a Switch instead, which better communicates "setting" semantics.

### 主题 API

```json
{
  "targets": [
    {
      "className": "astryx-toggle-button-group"
    },
    {
      "className": "astryx-toggle-button",
      "states": [
        "isPressed"
      ],
      "visualProps": [
        "elevation"
      ]
    }
  ]
}
```

## ToggleButtonGroup



### 无障碍

- **Text label**: The label must have at least 4.5:1 contrast with the button background when selected and unselected. For Hover and Pointer down, measure the final background after the overlay is applied. — 4.5:1
- **Essential icon or spinner arc**: An icon-only ToggleButton must have at least 3:1 contrast between its icon and button background. The moving spinner arc must also meet 3:1. An icon beside a visible label does not need its own check. — 3:1
- **Selected state indicator**: The selected background must reach 3:1 only when users need it to tell selected from unselected. Label weight or a changed icon can also show selection. — 3:1 if relied upon
- **Visible control boundary**: The button edge needs 3:1 contrast only when users need it to see the control. A visible label or icon can show the control instead. — 3:1 if needed
- **Keyboard focus indicator**: The focus outline must have at least 3:1 contrast with the area around the button. Check both selected and unselected states. — 3:1
- **Disabled appearance**: Disabled controls do not need to meet these contrast ratios. — Not required

### 组件结构

- **Icon**: A leading icon that represents the toggle action, like a star for favorite or bold "B" for formatting.
- **Pressed icon**: An alternate icon shown when pressed: typically a filled version of the default icon to reinforce the active state.
- **Label**: The visible text or accessible name. For icon-only toggles, used as the aria-label and auto-tooltip.
- **Spinner**: Replaces the icon during async operations triggered by pressedChangeAction.

## Toggle Button Group

将切换按钮分组，支持单选或多选行为。通过 type 判别联合类型实现类型安全。

| 属性 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| children * | ReactNode |  | ToggleButton 子元素；每个成员都需要 value。分组控制按下状态，并忽略成员的 isPressed、onPressedChange 和 pressedChangeAction。激活成员只调用分组的 onChange，不启动成员的 Action 过渡。 |
| label * | string |  | 分组的无障碍标签 (aria-label)。 |
| type | 'single' \| 'multiple' | 'single' | 选择模式。single 允许单个激活，multiple 允许多个。 |
| value * | string \| null \| string[] |  | 当前选中的值。类型取决于选择模式。 |
| onChange * | (value: string \| null \| string[]) => void |  | 选择变更时的回调。 |
| orientation | 'horizontal' \| 'vertical' | 'horizontal' | 按钮组的布局方向。 |
| size | 'sm' \| 'md' \| 'lg' | 'md' | 分组内按钮的默认尺寸。单个按钮可覆盖。 |
| isDisabled | boolean | false | 分组内所有按钮是否禁用。 |
| xstyle | StyleXStyles |  | StyleX 样式，用于布局自定义。必须是 stylex.create() 的值。 |
| data-testid | string |  | 自动化测试的选择器。 |


## 完整示例的额外依赖

部分示例使用独立图标包。示例清单中的每条安装命令包含该示例实际需要的依赖；若要运行本页全部示例，还需安装：

```bash
npm install @heroicons/react@2.2.0
```

---

JGuang 全部资源索引: https://jiguang132.com/llms.txt
