# Checkbox 复选框 · HeroUI

> 复选框允许用户从多个独立选项中选择多项，或将单个独立选项标记为已选。

- 页面: https://jiguang132.com/zh/systems/heroui/docs/components/checkbox
- 改编自: HeroUI 文档 (Apache-2.0) @ 60edd8ed751b1d2a270623fbb182bbcfa8baa9af

## 引入

```tsx
import { Checkbox } from '@heroui/react';
```

### 用法


> 示例 `checkbox-basic`: 交互预览见 https://jiguang132.com/zh/systems/heroui/docs/components/checkbox


### 组件结构

引入 Checkbox 后，可通过点语法访问各个部分。

```tsx
import { Checkbox, Description, FieldError } from '@heroui/react';

export default () => (
  <Checkbox>
    <Checkbox.Content>
      <Checkbox.Control>
        <Checkbox.Indicator />
      </Checkbox.Control>
      Label {/* 纯文本 —— 可点击的标签，同时作为无障碍名称 */}
    </Checkbox.Content>
    <Description /> {/* 可选 — 字段级帮助文本 */}
    <FieldError /> {/* 可选 — 校验错误信息 */}
  </Checkbox>
);
```

### 禁用


> 示例 `checkbox-disabled`: 交互预览见 https://jiguang132.com/zh/systems/heroui/docs/components/checkbox


### 默认选中


> 示例 `checkbox-default-selected`: 交互预览见 https://jiguang132.com/zh/systems/heroui/docs/components/checkbox


### 受控


> 示例 `checkbox-controlled`: 交互预览见 https://jiguang132.com/zh/systems/heroui/docs/components/checkbox


### 不定状态


> 示例 `checkbox-indeterminate`: 交互预览见 https://jiguang132.com/zh/systems/heroui/docs/components/checkbox


### 外部标签


> 示例 `checkbox-external-label`: 交互预览见 https://jiguang132.com/zh/systems/heroui/docs/components/checkbox


### 带说明


> 示例 `checkbox-with-description`: 交互预览见 https://jiguang132.com/zh/systems/heroui/docs/components/checkbox


### 渲染 props


> 示例 `checkbox-render-props`: 交互预览见 https://jiguang132.com/zh/systems/heroui/docs/components/checkbox


### 表单集成


> 示例 `checkbox-form`: 交互预览见 https://jiguang132.com/zh/systems/heroui/docs/components/checkbox


### 无效


> 示例 `checkbox-invalid`: 交互预览见 https://jiguang132.com/zh/systems/heroui/docs/components/checkbox


### 自定义指示器


> 示例 `checkbox-custom-indicator`: 交互预览见 https://jiguang132.com/zh/systems/heroui/docs/components/checkbox


### 全圆角


> 示例 `checkbox-full-rounded`: 交互预览见 https://jiguang132.com/zh/systems/heroui/docs/components/checkbox


### 变体

Checkbox 支持两种视觉变体：

- **`primary`**（默认）— 常规样式与默认背景，适用于大多数场景
- **`secondary`** — 弱强调变体，适合用于 Surface 等组件内部


> 示例 `checkbox-variants`: 交互预览见 https://jiguang132.com/zh/systems/heroui/docs/components/checkbox


### 自定义渲染函数


> 示例 `checkbox-custom-render-function`: 交互预览见 https://jiguang132.com/zh/systems/heroui/docs/components/checkbox


## 样式

### 传入 Tailwind CSS 类

你可以单独定制各个 Checkbox：

```tsx
import { Checkbox, Label } from '@heroui/react';

function CustomCheckbox() {
  return (
    <Checkbox name="custom">
      <Checkbox.Content>
        <Checkbox.Control className="border-2 border-purple-500 data-[selected=true]:bg-purple-500">
          <Checkbox.Indicator className="text-white" />
        </Checkbox.Control>
        Custom Checkbox
      </Checkbox.Content>
    </Checkbox>
  );
}
```

### 自定义组件类

若要自定义 Checkbox 的组件类名，可使用 `@layer components` 指令。
  
[了解更多](https://tailwindcss.com/docs/adding-custom-styles#adding-component-classes)。

```css
@layer components {
  .checkbox {
    @apply inline-flex gap-3 items-center;
  }

  .checkbox__control {
    @apply size-5 border-2 border-gray-400 rounded data-[selected=true]:bg-blue-500 data-[selected=true]:border-blue-500;

    /* Animated background indicator */
    &::before {
      @apply bg-accent pointer-events-none absolute inset-0 z-0 origin-center scale-50 rounded-md opacity-0 content-[''];
      
      transition:
        scale 200ms linear,
        opacity 200ms linear,
        background-color 200ms ease-out;
    }

    /* Show indicator when selected */
    &[data-selected="true"]::before {
      @apply scale-100 opacity-100;
    }
  }

  .checkbox__indicator {
    @apply text-white;
  }

  .checkbox__content {
    @apply items-center gap-3;
  }
}
```

HeroUI 遵循 [BEM](https://getbem.com/) 方法论，确保组件变体与状态可复用且易于定制。

### CSS 类

Checkbox 使用以下 CSS 类（[查看源码样式](https://github.com/heroui-inc/heroui/blob/v3/packages/styles/components/checkbox.css)）：

- `.checkbox` - Checkbox 根容器
- `.checkbox__content` - 包裹控件与标签文本的可点击 label
- `.checkbox__control` - Checkbox 控件方框
- `.checkbox__indicator` - Checkbox 勾选指示器

### 交互状态

Checkbox 同时支持 CSS 伪类与 data 属性，以获得更好的灵活性：

- **选中**：`[data-selected="true"]` 或 `[aria-checked="true"]`（显示勾选与背景色变化）
- **不定**：`[data-indeterminate="true"]`（以横线表示不定状态）
- **无效**：`[data-invalid="true"]` 或 `[aria-invalid="true"]`（以危险色显示错误状态）
- **悬停**：`:hover` 或 `[data-hovered="true"]`（交互状态在 `Checkbox.Control` / 按钮上）
- **焦点**：`:focus-visible` 或 `[data-focus-visible="true"]`（显示焦点环，作用于按钮）
- **禁用**：`[data-disabled="true"]`（降低透明度并禁用指针事件）
- **按下**：`:active` 或 `[data-pressed="true"]`

## API 参考

### Checkbox Props

继承自 [React Aria CheckboxField](https://react-spectrum.adobe.com/react-aria/Checkbox.html)。

| Prop | 类型 | 默认值 | 描述 |
|------|------|--------|------|
| `isSelected` | `boolean` | `false` | Checkbox 是否选中 |
| `defaultSelected` | `boolean` | `false` | Checkbox 默认是否选中（非受控） |
| `isIndeterminate` | `boolean` | `false` | Checkbox 是否处于不定状态 |
| `isDisabled` | `boolean` | `false` | Checkbox 是否禁用 |
| `isInvalid` | `boolean` | `false` | Checkbox 是否无效 |
| `isReadOnly` | `boolean` | `false` | Checkbox 是否只读 |
| `isRequired` | `boolean` | `false` | Checkbox 是否必须选中 |
| `validate` | `(value: boolean) => ValidationError \| true \| null \| undefined` | - | 自定义校验函数 |
| `validationBehavior` | `'native' \| 'aria'` | `'native'` | 使用原生 HTML 校验或 ARIA 校验 |
| `variant` | `"primary" \| "secondary"` | `"primary"` | 组件的视觉变体。`primary` 为默认带阴影样式。`secondary` 为弱强调、无阴影变体，适合用于 surface 上。 |
| `name` | `string` | - | input 元素的 name，用于提交 HTML 表单 |
| `value` | `string` | - | input 元素的 value，用于提交 HTML 表单 |
| `onChange` | `(isSelected: boolean) => void` | - | Checkbox 值变化时调用 |
| `children` | `React.ReactNode \| (values: CheckboxFieldRenderProps) => React.ReactNode` | - | Checkbox 内容或字段级渲染 prop |
| `render` | `DOMRenderFunction<keyof React.JSX.IntrinsicElements, CheckboxFieldRenderProps>` | - | 通过自定义渲染函数覆盖默认的 DOM 元素。 |

### Checkbox.Content Props

包裹控件与标签文本的可点击 `<label>`。请把 `Checkbox.Control` 与 `Label` 放在它内部；`Description`/`FieldError` 作为 `Checkbox.Content` 的兄弟节点。对于没有标签的 checkbox，省略 `Label` 并在 `Checkbox` 上传入 `aria-label`。

| Prop | 类型 | 默认值 | 描述 |
|------|------|--------|------|
| `children` | `React.ReactNode \| (values: CheckboxButtonRenderProps) => React.ReactNode` | - | 按钮内容（控件 + 标签），或按钮级渲染 prop |
| `className` | `string \| (values: CheckboxButtonRenderProps) => string` | - | 应用到可点击 label 的类名 |

### CheckboxFieldRenderProps

在根 `Checkbox` 上使用渲染 prop 时，提供以下字段级值：

| Prop | 类型 | 描述 |
|------|------|------|
| `isSelected` | `boolean` | Checkbox 当前是否选中 |
| `isIndeterminate` | `boolean` | Checkbox 是否处于不定状态 |
| `isDisabled` | `boolean` | Checkbox 是否禁用 |
| `isReadOnly` | `boolean` | Checkbox 是否只读 |
| `isInvalid` | `boolean` | Checkbox 是否无效 |
| `isRequired` | `boolean` | Checkbox 是否必填 |

### CheckboxButtonRenderProps

`Checkbox.Control` 与 `Checkbox.Indicator` 使用按钮级渲染 prop（`isHovered`、`isPressed`、`isFocusVisible` 等）。将函数作为 `Checkbox.Control` 或 `Checkbox.Indicator` 的子元素即可访问。

---

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