106k
New

复选框

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

By clicking this checkbox, you agree to the terms.

"use client"

import { Checkbox } from "@/components/ui/checkbox"

安装

pnpm dlx shadcn@latest add checkbox

使用

import { Checkbox } from "@/components/ui/checkbox"
<Checkbox />

选中状态

使用 defaultChecked 处理非受控复选框,或者使用 checkedonCheckedChange 来控制状态。

import * as React from "react"
 
export function Example() {
  const [checked, setChecked] = React.useState(false)
 
  return <Checkbox checked={checked} onCheckedChange={setChecked} />
}

无效状态

在复选框上设置 aria-invalid,并在字段包装组件上设置 data-invalid, 以显示无效的样式。

import { Checkbox } from "@/components/ui/checkbox"
import { Field, FieldGroup, FieldLabel } from "@/components/ui/field"

示例

基础

配合 FieldFieldLabel 使用复选框,以实现正确的布局和标签。

import { Checkbox } from "@/components/ui/checkbox"
import { Field, FieldGroup, FieldLabel } from "@/components/ui/field"

描述

使用 FieldContentFieldDescription 来显示辅助文字。

By clicking this checkbox, you agree to the terms and conditions.

import { Checkbox } from "@/components/ui/checkbox"
import {
  Field,

禁用

使用 disabled 属性来禁止交互,并在 <Field> 组件添加 data-disabled 属性,以应用禁用样式。

import { Checkbox } from "@/components/ui/checkbox"
import { Field, FieldGroup, FieldLabel } from "@/components/ui/field"

使用多个字段来创建复选框列表。

Show these items on the desktop:

Select the items you want to show on the desktop.

import { Checkbox } from "@/components/ui/checkbox"
import {
  Field,

表格

NameEmailRole
Sarah Chensarah.chen@example.comAdmin
Marcus Rodriguezmarcus.rodriguez@example.comUser
Priya Patelpriya.patel@example.comUser
David Kimdavid.kim@example.comEditor
"use client"

import * as React from "react"

API 参考

更多信息请参考 Radix UI 文档。