# 复选框

一种允许用户在选中和未选中之间切换的控件。

## Features

- 支持不确定状态。

- 完全的键盘导航。

- 可以是受控或非受控的。

## [结构](#结构)

导入所有部分并将它们组合在一起。

```jsx
import { Checkbox } from "radix-ui";

export default () => (
  <Checkbox.Root>
    <Checkbox.Indicator />
  </Checkbox.Root>
);
```

## [API 参考](#api-参考)

### [Root](#root)

包含复选框的所有部分。当在 `form` 中使用时，将渲染一个 `input` 以确保事件正确传播。

| Prop              | Type                         | Default          |
| ----------------- | ---------------------------- | ---------------- |
| `asChild`         | `boolean`                    | `false`          |
| `defaultChecked`  | `boolean \| 'indeterminate'` | No default value |
| `checked`         | `boolean \| 'indeterminate'` | No default value |
| `onCheckedChange` | `function`                   | No default value |
| `disabled`        | `boolean`                    | No default value |
| `required`        | `boolean`                    | No default value |
| `name`            | `string`                     | No default value |
| `value`           | `string`                     | `on`             |

| Data attribute    | Values                                        |
| ----------------- | --------------------------------------------- |
| `[data-state]`    | `"checked" \| "unchecked" \| "indeterminate"` |
| `[data-disabled]` | 禁用时存在                                    |

### [Indicator](#indicator)

在复选框处于选中或不确定状态时渲染。您可以直接为此元素设置样式，或者可以将其作为包装器放入图标，或者两者都可以。

| Prop         | Type      | Default          |
| ------------ | --------- | ---------------- |
| `asChild`    | `boolean` | `false`          |
| `forceMount` | `boolean` | No default value |

| Data attribute    | Values                                        |
| ----------------- | --------------------------------------------- |
| `[data-state]`    | `"checked" \| "unchecked" \| "indeterminate"` |
| `[data-disabled]` | 禁用时存在                                    |

## [示例](#示例)

### [不确定状态](#不确定状态)

您可以通过控制其状态将复选框设置为 `indeterminate`。

```jsx
import { DividerHorizontalIcon, CheckIcon } from "@radix-ui/react-icons";

import { Checkbox } from "radix-ui";

export default () => {
  const [checked, setChecked] = React.useState("indeterminate");

  return (
    <>
      <StyledCheckbox checked={checked} onCheckedChange={setChecked}>
        <Checkbox.Indicator>
          {checked === "indeterminate" && <DividerHorizontalIcon />}

          {checked === true && <CheckIcon />}
        </Checkbox.Indicator>
      </StyledCheckbox>

      <button
        type="button"
        onClick={() =>
          setChecked((prevIsChecked) =>
            prevIsChecked === "indeterminate" ? false : "indeterminate",
          )
        }
      >
        切换不确定状态
      </button>
    </>
  );
};
```

## [可访问性](#可访问性)

遵循 [三态复选框 WAI-ARIA 设计模式](https://www.w3.org/WAI/ARIA/apg/patterns/checkbox)。

### [键盘交互](#键盘交互)

| Key     | Description           |
| ------- | --------------------- |
| `Space` | 选中/取消选中复选框。 |

<!--$-->

<!--/$-->
