选择一个或多个选项,可以单独选,也可以成组选。

用复选框表示一个可以勾选或取消勾选的选项。几个选项属于同一个值时,用分组。

<script lang="ts">
  import { CheckIcon } from "@lucide/svelte"
  import { Checkbox, CheckboxIndicator } from "@ui-sdk/svelte/checkbox"
</script>

<label data-slot="label">
  <Checkbox>
    <CheckboxIndicator>
      <CheckIcon aria-hidden="true" />
    </CheckboxIndicator>
  </Checkbox>
  Accept terms and conditions
</label>
点击复选框或它的标签,或聚焦它后按 Space,接受条款。

安装

npm install @ui-sdk/svelte @ui-sdk/core

组合

用下面的组合构建一个 Checkbox:

Checkbox
└── CheckboxIndicator

把复选框和它的文字包在一个 label 里。复选框已勾选或处于混合状态时,指示器会显示。

用法

导入部件并把它们组合起来:

<script lang="ts">
  import { Checkbox, CheckboxIndicator } from "@ui-sdk/svelte/checkbox"
</script>

<label>
  <Checkbox>
    <CheckboxIndicator aria-hidden="true">✓</CheckboxIndicator>
  </Checkbox>
  Accept terms and conditions
</label>

描述

选项需要更多说明时,用 FieldLabel 和 FieldDescription。字段会把标签和描述都连接到复选框。

<script lang="ts">
  import { CheckIcon } from "@lucide/svelte"
  import { Checkbox, CheckboxIndicator } from "@ui-sdk/svelte/checkbox"
  import { Field, FieldDescription, FieldLabel } from "@ui-sdk/svelte/field"
</script>

<Field>
  <Checkbox>
    <CheckboxIndicator>
      <CheckIcon aria-hidden="true" />
    </CheckboxIndicator>
  </Checkbox>
  <div data-slot="stack">
    <FieldLabel>Accept terms and conditions</FieldLabel>
    <FieldDescription>
      By clicking this checkbox, you agree to the terms and conditions.
    </FieldDescription>
  </div>
</Field>
点击 Accept terms and conditions。字段把标签和描述连接到复选框。

禁用

disabled 阻止聚焦和更改,并让复选框不参与表单提交。禁用的 fieldset 也一样。

<script lang="ts">
  import { CheckIcon } from "@lucide/svelte"
  import { Checkbox, CheckboxIndicator } from "@ui-sdk/svelte/checkbox"
</script>

<div data-slot="stack">
  <label data-slot="label">
    <Checkbox defaultChecked>
      <CheckboxIndicator>
        <CheckIcon aria-hidden="true" />
      </CheckboxIndicator>
    </Checkbox>
    Product updates
  </label>
  <label data-slot="label">
    <Checkbox defaultChecked disabled>
      <CheckboxIndicator>
        <CheckIcon aria-hidden="true" />
      </CheckboxIndicator>
    </Checkbox>
    Security alerts
  </label>
</div>
Security alerts 始终开启,所以那个复选框处于禁用状态。点击它的标签不会改变勾选状态。

只读

readOnly 让复选框保持可聚焦并参与表单提交,同时阻止用户更改它。

<script lang="ts">
  import { CheckIcon } from "@lucide/svelte"
  import { Checkbox, CheckboxIndicator } from "@ui-sdk/svelte/checkbox"
  import { Field, FieldDescription, FieldLabel } from "@ui-sdk/svelte/field"
</script>

<Field>
  <Checkbox name="two-factor" defaultChecked readOnly>
    <CheckboxIndicator>
      <CheckIcon aria-hidden="true" />
    </CheckboxIndicator>
  </Checkbox>
  <div data-slot="stack">
    <FieldLabel>Require two-factor authentication</FieldLabel>
    <FieldDescription>
      Your organization requires this setting.
    </FieldDescription>
  </div>
</Field>
按 Tab 到达已勾选的复选框。按 Space 或点击都不会改变这个设置。

不确定

不确定的复选框表示一个部分勾选的集合。它有 aria-checked="mixed" 和 data-indeterminate。按压会勾选它;只有你的代码能把它放回混合状态。

从 defaultChecked="indeterminate" 开始,或把 "indeterminate" 作为受控值传入。指示器的状态告诉它该显示哪个图标。父复选框会替你从分组推导这个状态。

<Checkbox defaultChecked="indeterminate">
  <CheckboxIndicator>
    {#snippet children(state)}
      {#if state.indeterminate}<MinusIcon />{:else}<CheckIcon />{/if}
    {/snippet}
  </CheckboxIndicator>
</Checkbox>

受控

用 bind:checked 自己持有值。createCheckboxController() 创建的控制器可以从任何地方更改它,比如下面的 Toggle 按钮。

控制台
<script lang="ts">
  import { CheckIcon } from "@lucide/svelte"
  import {
    Checkbox,
    CheckboxIndicator,
    createCheckboxController,
    type CheckedState,
  } from "@ui-sdk/svelte/checkbox"
  import { useLog } from "./log"

  const log = useLog()
  const updates = createCheckboxController()
  let checked = $state<CheckedState>(false)
</script>

<div data-slot="stack">
  <div data-slot="controls">
    <button type="button" onclick={() => updates.toggle()}>Toggle</button>
  </div>
  <label data-slot="label">
    <Checkbox
      bind:checked
      controller={updates}
      onCheckedChange={(next, details) =>
        log(
          `${next === "indeterminate" ? "Mixed" : next ? "Checked" : "Unchecked"} (${details.reason})`
        )}
    >
      <CheckboxIndicator>
        <CheckIcon aria-hidden="true" />
      </CheckboxIndicator>
    </Checkbox>
    Email me about product updates
  </label>
</div>
更改复选框,或按 Toggle。控制台会记录每次变更及其原因。

表单

设置 name 和 value,让已勾选的复选框进入原生表单。未勾选和混合状态的复选框不提交任何内容。默认值是 "on"。独立的复选框可以共用一个 name 来提交多个值;应用还需要一份已勾选值的列表时,用分组。

required 会阻止提交,直到复选框被勾选。Reset 会把它恢复到 defaultChecked。把 form 设为表单的 id,就能从页面其他地方加入该表单。

控制台
<script lang="ts">
  import { CheckIcon } from "@lucide/svelte"
  import { Checkbox, CheckboxIndicator } from "@ui-sdk/svelte/checkbox"
  import { Field, FieldDescription, FieldLabel } from "@ui-sdk/svelte/field"
  import { useLog } from "./log"

  const log = useLog()

  function onSubmit(event: SubmitEvent & { currentTarget: HTMLFormElement }) {
    event.preventDefault()
    const entries = [...new FormData(event.currentTarget)].map(
      ([name, value]) => `${name}=${value}`
    )
    log(entries.length ? `Submitted ${entries.join("&")}` : "Submitted nothing")
  }
</script>

<form data-slot="stack" onsubmit={onSubmit}>
  <Field>
    <Checkbox name="terms" value="yes" required>
      <CheckboxIndicator>
        <CheckIcon aria-hidden="true" />
      </CheckboxIndicator>
    </Checkbox>
    <div data-slot="stack">
      <FieldLabel>Accept terms and conditions</FieldLabel>
      <FieldDescription
        >You agree to our Terms of Service and Privacy Policy.</FieldDescription
      >
    </div>
  </Field>
  <Field>
    <Checkbox name="newsletter" value="weekly" defaultChecked>
      <CheckboxIndicator>
        <CheckIcon aria-hidden="true" />
      </CheckboxIndicator>
    </Checkbox>
    <div data-slot="stack">
      <FieldLabel>Send me the weekly newsletter</FieldLabel>
      <FieldDescription
        >Product news and tips, once a week. Unsubscribe anytime.</FieldDescription
      >
    </div>
  </Field>
  <div data-slot="row">
    <button type="submit">Create Account</button>
    <button type="reset">Reset</button>
  </div>
</form>
在条款未勾选的情况下创建账户,查看原生校验,然后接受条款并重试。控制台会记录提交的内容,Reset 会恢复默认值。

分组

CheckboxGroup 维护一份已勾选值的列表。每个复选框提供它的 value;分组按复选框出现的顺序返回选中的值。用 aria-label、aria-labelledby 或 Field 为分组命名。

<script lang="ts">
  import { CheckIcon } from "@lucide/svelte"
  import {
    Checkbox,
    CheckboxGroup,
    CheckboxIndicator,
  } from "@ui-sdk/svelte/checkbox"

  const toppings = [
    { value: "cheese", label: "Cheese" },
    { value: "mushrooms", label: "Mushrooms" },
    { value: "olives", label: "Olives" },
    { value: "peppers", label: "Peppers" },
  ]
</script>

<div data-slot="stack">
  <h3 id="basic-toppings">Toppings</h3>
  <CheckboxGroup aria-labelledby="basic-toppings" defaultValue={["cheese"]}>
    {#each toppings as topping (topping.value)}
      <label data-slot="label">
        <Checkbox value={topping.value}>
          <CheckboxIndicator>
            <CheckIcon aria-hidden="true" />
          </CheckboxIndicator>
        </Checkbox>
        {topping.label}
      </label>
    {/each}
  </CheckboxGroup>
</div>
选择多种配料。分组维护一份已勾选值的列表。

父复选框

添加一个带 parent 的复选框,用来勾选或取消勾选整个分组。所有值都选中时它处于勾选状态,一个都没有时处于未勾选状态,其余情况为混合状态。它用 aria-controls 指向子复选框,自身不提交任何内容。

把 allValues 传给分组,让父复选框在首次渲染时就有正确的状态,在服务器上也是如此。否则它要等复选框挂载后才能发现这些值。

<script lang="ts">
  import { CheckIcon, MinusIcon } from "@lucide/svelte"
  import {
    Checkbox,
    CheckboxGroup,
    CheckboxIndicator,
  } from "@ui-sdk/svelte/checkbox"

  const toppings = [
    { value: "cheese", label: "Cheese" },
    { value: "mushrooms", label: "Mushrooms" },
    { value: "olives", label: "Olives" },
    { value: "peppers", label: "Peppers" },
  ]
</script>

<div data-slot="stack">
  <h3 id="parent-toppings">Toppings</h3>
  <CheckboxGroup
    aria-labelledby="parent-toppings"
    defaultValue={["cheese", "olives"]}
    allValues={toppings.map((topping) => topping.value)}
  >
    <label data-slot="label">
      <Checkbox parent>
        <CheckboxIndicator>
          <CheckIcon aria-hidden="true" />
          <MinusIcon aria-hidden="true" />
        </CheckboxIndicator>
      </Checkbox>
      Select all
    </label>
    <div data-slot="stack">
      {#each toppings as topping (topping.value)}
        <label data-slot="label">
          <Checkbox value={topping.value}>
            <CheckboxIndicator>
              <CheckIcon aria-hidden="true" />
            </CheckboxIndicator>
          </Checkbox>
          {topping.label}
        </label>
      {/each}
    </div>
  </CheckboxGroup>
</div>
Select all 会勾选每一种配料。取消勾选一种配料,Select all 就进入混合状态。

禁用的分组

禁用分组可以锁定每个复选框,或者禁用一个子项,只固定那个值。父复选框只会更改启用的子项。

<script lang="ts">
  import { CheckIcon, MinusIcon } from "@lucide/svelte"
  import {
    Checkbox,
    CheckboxGroup,
    CheckboxIndicator,
  } from "@ui-sdk/svelte/checkbox"

  const backups = [
    { value: "photos", label: "Photos" },
    { value: "documents", label: "Documents" },
    { value: "messages", label: "Messages" },
  ]

  const folders = [
    { value: "desktop", label: "Desktop", disabled: true },
    { value: "projects", label: "Projects", disabled: false },
    { value: "downloads", label: "Downloads", disabled: false },
  ]
</script>

<div data-slot="stack">
  <div data-slot="stack">
    <h3 id="disabled-backups">Backups</h3>
    <p data-slot="hint">Managed by your organization.</p>
    <CheckboxGroup
      aria-labelledby="disabled-backups"
      defaultValue={["photos", "documents"]}
      disabled
    >
      {#each backups as item (item.value)}
        <label data-slot="label">
          <Checkbox value={item.value}>
            <CheckboxIndicator>
              <CheckIcon aria-hidden="true" />
            </CheckboxIndicator>
          </Checkbox>
          {item.label}
        </label>
      {/each}
    </CheckboxGroup>
  </div>
  <div data-slot="stack">
    <h3 id="disabled-folders">Sync folders</h3>
    <CheckboxGroup
      aria-labelledby="disabled-folders"
      defaultValue={["desktop"]}
      allValues={folders.map((item) => item.value)}
    >
      <label data-slot="label">
        <Checkbox parent>
          <CheckboxIndicator>
            <CheckIcon aria-hidden="true" />
            <MinusIcon aria-hidden="true" />
          </CheckboxIndicator>
        </Checkbox>
        Select all
      </label>
      <div data-slot="stack">
        {#each folders as item (item.value)}
          <label data-slot="label">
            <Checkbox value={item.value} disabled={item.disabled}>
              <CheckboxIndicator>
                <CheckIcon aria-hidden="true" />
              </CheckboxIndicator>
            </Checkbox>
            {item.label}
          </label>
        {/each}
      </div>
    </CheckboxGroup>
  </div>
</div>
Backups 分组已禁用。在 Sync folders 中,Select all 会更改启用的文件夹,而 Desktop 保持勾选。

受控的分组

用 bind:value 自己持有选中的值。控制器可以替换这份列表,就像下面的 Select Weekdays 和 Clear 那样。

控制台
<script lang="ts">
  import { CheckIcon } from "@lucide/svelte"
  import {
    Checkbox,
    CheckboxGroup,
    CheckboxIndicator,
    createCheckboxGroupController,
  } from "@ui-sdk/svelte/checkbox"
  import { useLog } from "./log"

  const days = [
    { value: "mon", label: "Monday" },
    { value: "tue", label: "Tuesday" },
    { value: "wed", label: "Wednesday" },
    { value: "thu", label: "Thursday" },
    { value: "fri", label: "Friday" },
    { value: "sat", label: "Saturday" },
    { value: "sun", label: "Sunday" },
  ]

  const weekdays = ["mon", "tue", "wed", "thu", "fri"]

  const log = useLog()
  const schedule = createCheckboxGroupController()
  let value = $state(["mon", "tue"])
</script>

<div data-slot="stack">
  <div data-slot="controls">
    <button type="button" onclick={() => schedule.setValue(weekdays)}
      >Select Weekdays</button
    >
    <button type="button" onclick={() => schedule.setValue([])}>Clear</button>
  </div>
  <h3 id="controlled-days">Working days</h3>
  <CheckboxGroup
    bind:value
    aria-labelledby="controlled-days"
    controller={schedule}
    onValueChange={(next, details) => {
      const names = days
        .filter((day) => next.includes(day.value))
        .map((day) => day.label)
      log(`${names.join(", ") || "No days"} (${details.reason})`)
    }}
  >
    {#each days as day (day.value)}
      <label data-slot="label">
        <Checkbox value={day.value}>
          <CheckboxIndicator>
            <CheckIcon aria-hidden="true" />
          </CheckboxIndicator>
        </Checkbox>
        {day.label}
      </label>
    {/each}
  </CheckboxGroup>
</div>
选择工作日,或按 Select Weekdays 或 Clear。控制台会记录分组的值以及变更原因。

表单中的分组

在分组上设置 name,把每个已勾选的值都以该 name 提交。required 要求至少选择一项,Reset 会恢复 defaultValue。disabled 和 form 选项与单个复选框相同。

在字段中,字段提供分组的标签和描述,FieldError 会在选择让分组通过校验之前就地显示校验消息。表单与校验涵盖了共用的字段行为。

控制台
<script lang="ts">
  import { CheckIcon } from "@lucide/svelte"
  import {
    Checkbox,
    CheckboxGroup,
    CheckboxIndicator,
  } from "@ui-sdk/svelte/checkbox"
  import {
    Field,
    FieldDescription,
    FieldError,
    FieldLabel,
  } from "@ui-sdk/svelte/field"
  import { useLog } from "./log"

  const channels = [
    { value: "email", label: "Email" },
    { value: "sms", label: "SMS" },
    { value: "push", label: "Push notifications" },
  ]

  const log = useLog()

  function onSubmit(event: SubmitEvent & { currentTarget: HTMLFormElement }) {
    event.preventDefault()
    const entries = [...new FormData(event.currentTarget)].map(
      ([name, value]) => `${name}=${value}`
    )
    log(`Saved ${entries.join("&")}`)
  }
</script>

<form data-slot="stack" onsubmit={onSubmit}>
  <Field>
    <FieldLabel>Notifications</FieldLabel>
    <FieldDescription
      >Choose how we tell you about your orders.</FieldDescription
    >
    <CheckboxGroup name="notifications" required>
      {#each channels as channel (channel.value)}
        <label data-slot="label">
          <Checkbox value={channel.value}>
            <CheckboxIndicator>
              <CheckIcon aria-hidden="true" />
            </CheckboxIndicator>
          </Checkbox>
          {channel.label}
        </label>
      {/each}
    </CheckboxGroup>
    <div>
      <FieldError>Choose at least one way to be notified.</FieldError>
    </div>
  </Field>
  <button type="submit">Save</button>
</form>
什么都不勾选就 Save,查看就地显示的错误。选择一种通知方式并保存;控制台会记录提交的值。

表格

同一个父复选框可以从表格表头中选择行。每一行提供它的值和无障碍名称。

控制台
<script lang="ts">
  import { CheckIcon, MinusIcon } from "@lucide/svelte"
  import {
    Checkbox,
    CheckboxGroup,
    CheckboxIndicator,
  } from "@ui-sdk/svelte/checkbox"
  import { useLog } from "./log"

  const people = [
    {
      id: "hollis",
      name: "Hollis Grant",
      email: "hollis@example.com",
      role: "Owner",
    },
    {
      id: "ines",
      name: "Inès Moreau",
      email: "ines@example.com",
      role: "Editor",
    },
    {
      id: "kofi",
      name: "Kofi Mensah",
      email: "kofi@example.com",
      role: "Viewer",
    },
    {
      id: "wren",
      name: "Wren Takahashi",
      email: "wren@example.com",
      role: "Editor",
    },
  ]

  const log = useLog()
  let selected = $state(["hollis"])
</script>

<CheckboxGroup
  bind:value={selected}
  aria-label="Team members"
  onValueChange={(next) => log(`${next.length} of ${people.length} selected`)}
  allValues={people.map((person) => person.id)}
>
  <table>
    <caption data-slot="visually-hidden">Team members</caption>
    <thead>
      <tr>
        <th>
          <Checkbox aria-label="Select all" parent>
            <CheckboxIndicator>
              <CheckIcon aria-hidden="true" />
              <MinusIcon aria-hidden="true" />
            </CheckboxIndicator>
          </Checkbox>
        </th>
        <th>Name</th>
        <th>Email</th>
        <th>Role</th>
      </tr>
    </thead>
    <tbody>
      {#each people as person (person.id)}
        <tr>
          <td>
            <Checkbox value={person.id} aria-label={`Select ${person.name}`}>
              <CheckboxIndicator>
                <CheckIcon aria-hidden="true" />
              </CheckboxIndicator>
            </Checkbox>
          </td>
          <td>{person.name}</td>
          <td>{person.email}</td>
          <td>{person.role}</td>
        </tr>
      {/each}
    </tbody>
  </table>
</CheckboxGroup>
逐行选择,或使用表头里的 Select all。控制台会记录选中的行数。

动画

指示器出现时带有 data-starting-style,离开时带有 data-ending-style,并保持挂载直到退场结束。从这些状态过渡:

[data-slot="checkbox-indicator"] {
  transition:
    opacity 0.15s,
    scale 0.15s;

  &:is([data-starting-style], [data-ending-style]) {
    opacity: 0;
    scale: 0.5;
  }
}

keepMounted 让指示器在未勾选时也留在页面中,并带有 data-unchecked,用于同时展示两种状态的样式。

<script lang="ts">
  import { CheckIcon } from "@lucide/svelte"
  import { Checkbox, CheckboxIndicator } from "@ui-sdk/svelte/checkbox"

  const tasks = [
    { label: "Write the release notes", done: false },
    { label: "Update the changelog", done: true },
    { label: "Tag the release", done: false },
  ]
</script>

<div data-slot="stack">
  {#each tasks as task (task.label)}
    <label data-slot="label">
      <Checkbox defaultChecked={task.done}>
        <CheckboxIndicator>
          <CheckIcon aria-hidden="true" />
        </CheckboxIndicator>
      </Checkbox>
      {task.label}
    </label>
  {/each}
</div>
勾选再取消勾选一个任务。对勾会缩放并淡入,在卸载前淡出。

自定义渲染

复选框、指示器和分组都接受 render 片段,它接收要展开的 props 和部件的状态。把部件的 props 留在交互元素上,让它的角色、标签和键盘行为保持连接。

<script lang="ts">
  import { CheckIcon, PlusIcon } from "@lucide/svelte"
  import { Checkbox } from "@ui-sdk/svelte/checkbox"

  const topics = [
    { value: "design", label: "Design", checked: true },
    { value: "engineering", label: "Engineering", checked: false },
    { value: "marketing", label: "Marketing", checked: false },
    { value: "sales", label: "Sales", checked: false },
  ]
</script>

<fieldset>
  <legend>Topics you follow</legend>
  <div data-slot="row">
    {#each topics as topic (topic.value)}
      <Checkbox
        name="topics"
        value={topic.value}
        defaultChecked={topic.checked}
      >
        {#snippet render({ props, state })}
          <button {...props}>
            {#if state.checked}
              <CheckIcon />
            {:else}
              <PlusIcon />
            {/if}
            {topic.label}
          </button>
        {/snippet}
      </Checkbox>
    {/each}
  </div>
</fieldset>
选择主题。每个复选框渲染一个按钮,根据它的状态显示对勾或加号。

样式

用 data-checked、data-unchecked 和 data-indeterminate 表示勾选状态,用 data-disabled、data-readonly 和 data-required 表示其余状态。指示器会得到与它的复选框相同的状态属性。

每个部件都有一个 data-slot,比如 checkbox,它的状态属性列在数据属性下。

数据属性

Checkbox

[data-slot="checkbox"]

属性含义
data-checkedPresent while checked.
data-disabledPresent when disabled, by its own prop, a group or a <fieldset>.
data-readonlyPresent when read-only.
data-requiredPresent when required.
data-uncheckedPresent while unchecked.
data-indeterminatePresent while indeterminate.

CheckboxIndicator

[data-slot="checkbox-indicator"]

属性含义
data-checkedPresent while checked.
data-disabledPresent when disabled, by its own prop, a group or a <fieldset>.
data-readonlyPresent when read-only.
data-requiredPresent when required.
data-uncheckedPresent while unchecked.
data-indeterminatePresent while indeterminate.
data-starting-stylePresent for the indicator's first frame. Style the state you animate from.
data-ending-stylePresent while the indicator animates out. Style the state you animate to.

CheckboxGroup

[data-slot="checkbox-group"]

属性含义
data-disabledPresent when the group is disabled, by its own prop or a <fieldset>.
data-requiredPresent when at least one checkbox must be checked.

API 参考

属性和回调与下面相同,都是 Svelte props。checked 和分组的 value 可以用 bind:checked 和 bind:value 绑定。

Checkbox

checked?CheckedState
Whether it's checked. Pass it to control the checkbox.
defaultChecked?CheckedState
Whether it's checked at first, when uncontrolled. A form reset returns to it.
onCheckedChange?((checked: CheckedState, details: ChangeDetails<CheckboxCheckedChangeReason>) => void)
Runs when a user or a form reset wants to change it. details.reason says why, and details.cancel() stops it.
disabled?boolean
Disables it like a native control: it can't be focused or changed, and isn't submitted.
readOnly?boolean
Keeps it focusable and submitted, but stops changes.
required?boolean
Blocks form submission until it's checked, with the browser's own message.
name?string
The name it submits under. Without one, it submits nothing.
value?string
What it submits while checked.
form?string
The id of a form to belong to, when it isn't inside that form.
controller?{ toggle: (details?: Details) => boolean; getChecked: () => CheckedState; setChecked: (checked: CheckedState, details?: Details) => boolean; focus: () => void; }
Toggles it from anywhere. Create one with createCheckboxController().
parent?boolean
Makes it the parent of its group: it checks or unchecks every checkbox in the group, and shows checked, unchecked or indeterminate from them.
debug?boolean
Logs every state change with its reason to the console, in development builds.

CheckboxIndicator

keepMounted?boolean
Whether the indicator stays in the page while unchecked, so it can be styled or animated in both states.

CheckboxGroup

value?T[]
The checked checkboxes' values. Pass it to control the group.
defaultValue?T[]
The values checked at first, when uncontrolled. A form reset returns to them.
onValueChange?((value: T[], details: ChangeDetails<CheckboxGroupValueChangeReason>) => void)
Runs when a user or a form reset wants to change the value. details.reason says why, and details.cancel() stops it.
allValues?T[]
Every value a parent checkbox checks. Without it, the parent checks the checkboxes in the group. Pass it to render the parent right on the server.
disabled?boolean
Disables every checkbox in the group, and leaves them out of the form.
readOnly?boolean
Makes every checkbox in the group read-only: focusable and submitted, but presses don't change it.
required?boolean
Blocks form submission until at least one checkbox is checked, with the browser's own message.
name?string
The name every checkbox in the group submits under.
form?string
The id of a form to belong to, when the group isn't inside that form.
controller?{ getValue: () => T[]; setValue: (value: T[], details?: Details) => boolean; focus: () => void; }
Checks values from anywhere. Create one with createCheckboxGroupController().
debug?boolean
Logs every state change with its reason to the console, in development builds.

状态

render 和 children 片段收到什么。

checkedboolean
Whether it's checked. False while indeterminate.
indeterminateboolean
Whether it's "indeterminate", for a partly checked group. A press makes it checked.
disabledboolean
Whether it's disabled, by itself or by a <fieldset>.
readOnlyboolean
Whether it's read-only: it stays focusable and submitted, but presses don't change it.
requiredboolean
Whether a form won't submit until it's checked. Indeterminate doesn't count.

指示器收到相同的状态。

checkedboolean
Whether it's checked. False while indeterminate.
indeterminateboolean
Whether it's "indeterminate", for a partly checked group. A press makes it checked.
disabledboolean
Whether it's disabled, by itself or by a <fieldset>.
readOnlyboolean
Whether it's read-only: it stays focusable and submitted, but presses don't change it.
requiredboolean
Whether a form won't submit until it's checked. Indeterminate doesn't count.

分组:

valuestring[]
The checked values.
disabledboolean
Whether the group is disabled, by itself or by a <fieldset>.
readOnlyboolean
Whether the group is read-only: its checkboxes stay focusable and submitted, but presses don't change them.
requiredboolean
Whether a form won't submit until at least one of its checkboxes is checked.

原因

details.reason 说明勾选状态为什么改变。

pressMouseEvent | KeyboardEvent
A single-element control was pressed: a checkbox, a switch or a toggle.
resetnone
A form reset.
restorenone
The browser restored state, like after going back, or a saved value was read back from storage.
imperativenone
A controller or api call.

对分组来说,它说明已勾选的值为什么改变。

item-pressMouseEvent | KeyboardEvent
A member of a collection was chosen: a menu item, a tab, a radio or a checkbox item.
resetnone
A form reset.
restorenone
The browser restored state, like after going back, or a saved value was read back from storage.
imperativenone
A controller or api call.

Checkbox 控制器

用 createCheckboxController() 创建一个,并作为 controller 传入。

每个写入方法都接受可选的 { reason, event },像按压一样运行变更回调,并在变更被取消时返回 false。

toggle(details?)(details?: CheckboxChangeOptions | undefined) => boolean
Checks it, or unchecks it. An indeterminate checkbox becomes checked.
getChecked()() => CheckedState
Whether it's checked: true, false or "indeterminate".
setChecked(checked, details?)(checked: CheckedState, details?: CheckboxChangeOptions | undefined) => boolean
Sets whether it's checked, as a user would.
focus()() => void
Moves focus to it.

CheckboxGroup 控制器

用 createCheckboxGroupController() 创建一个,并作为 controller 传入。

它的写入方法与复选框控制器相同。

getValue()() => T[]
The checked values.
setValue(value, details?)(value: T[], details?: CheckboxGroupChangeOptions | undefined) => boolean
Sets the checked values, as a user would. A disabled group ignores it.
focus()() => void
Moves focus to the first enabled checkbox.

事件

回调先收到新状态或新值,再收到详情。绑定的值只在回调未被取消时更新。

Prop所属部件收到
bind:checkedCheckbox勾选状态
onCheckedChangeCheckbox(checked, details):true、false 或 "indeterminate",以及原因
bind:valueCheckboxGroup已勾选的值
onValueChangeCheckboxGroup(value, details):已勾选的值,以及原因

无障碍

复选框遵循 WAI-ARIA 复选框模式,分组的父复选框遵循它的混合复选框示例。Checkbox 渲染一个带 checkbox 角色的按钮,以及一个参与表单的隐藏原生复选框。下面每一行都是一个自动化测试。

键盘

Key作用
Tab移动到下一个复选框
Space勾选或取消勾选它,或勾选一个混合状态的复选框
Enter提交它的表单

经过测试的行为

Checkbox
  • Clicking toggles it.
  • Clicking its label toggles it.
  • Clicking a label around it toggles it once.
  • Space toggles it.
  • Enter submits the form and never toggles it.
  • Tab moves through checkboxes in order.
  • The indicator shows only while checked.
  • A change can be cancelled.
  • A controlled checkbox follows its value.
  • A read-only checkbox can be focused but not changed.
  • Exit keyframes keyed on data-unchecked play before the indicator unmounts.
  • An infinite exit animation still unmounts the indicator.

运行于 React、Vue 和 web components。

分组和父复选框:

  • The group is named by its label.
  • Starts on its default value.
  • Checking a checkbox adds its value to the group.
  • Every checked value submits under the group's name, in order.
  • A reset returns to the default value.
  • A required group blocks submission until one is checked.
Parent checkbox
  • Is mixed while some checkboxes are checked.
  • Checks every checkbox from mixed, then unchecks them all.
  • Is checked once every checkbox is.
  • Submits nothing itself.

运行于 React、Vue 和 web components。

在表单中:

  • The form submits every checked control's name and value.
  • Unchecked controls submit nothing.
  • A checkbox outside the form joins it with the form attribute.
  • Required controls block submission.
  • A form reset returns every control to its default.
  • A reset returns to the default value, not to nothing.
  • A disabled fieldset disables the controls inside it.
  • A read-only control still submits.
  • A user's change fires native input and change events on the form.

运行于 React、Vue 和 web components。

在模式基线之外:

Enhancements
  • The first invalid control takes focus in document order.
  • A later required field without an error part doesn't take focus from the first.
Form-associated custom elements
  • Take part in the form with no hidden input. 仅在 Web components 运行。
  • Report validity like native controls. 仅在 Web components 运行。
  • Have live checked and value properties. 仅在 Web components 运行。
  • Are named by their labels. 仅在 Web components 运行。

运行于 React、Vue 和 web components。

在每个经过测试的框架里,屏幕阅读器听到的内容相同,由虚拟屏幕阅读器录制:

  • Announcements while checking boxes with a keyboard.
  • Announcements while choosing a radio with a keyboard.

运行于 React、Vue 和 web components。