Перейти к основному содержанию

Обзор

Используйте Checkbox, когда каждый вариант можно выбрать независимо. Для взаимоисключающего выбора используйте группу радиокнопок.

Использование

Неуправляемое состояние

Используйте defaultChecked, чтобы задать начальное состояние флажка. Флажок управляет последующими изменениями.
Отмеченный флажок с именем добавляет свое значение в форму. Укажите uncheckedValue, если форма также должна отправлять значение, когда флажок не отмечен.

Внешний вид и взаимодействие

Сравните состояния «отмечено», «неопределённое» и «отключено», затем независимо выберите цвет, размер, форму и вариант. Состояние активных примеров можно переключать. Клавиша Tab переводит фокус на флажок, а пробел переключает его. Щелчок по его метке также переключает его. Используйте disabled, чтобы запретить взаимодействие, или readOnly, если значение должно оставаться неизменным, а элемент управления должен сохранять возможность получения фокуса. Передавайте смысл в метке, а не только с помощью цвета.

Управляемое состояние

Передайте checked и обновляйте его с помощью onCheckedChange, чтобы управлять тем же параметром в состоянии React. Функция обратного вызова получает следующее логическое значение и сведения о событии.

Неопределенное состояние

Флажок в неопределенном состоянии обозначает частичный выбор. Определяйте его на основе дочерних параметров независимо от состояния флажка.

Части и пользовательское содержимое

Checkbox собирает стилизованный корневой элемент и его стандартные значки установки и неопределённого состояния. Используйте Checkbox.Root с Checkbox.Indicator для управления содержимым индикатора. Root управляет состоянием и внешним видом поля; Indicator отображает предоставленное вами содержимое.
CheckboxRootProps и CheckboxIndicatorProps — это публичные типы, экспортируемые из twenty-ui/primitives/input. Обе части принимают нативные атрибуты, обработчики, ссылки, render и обратные вызовы className и style, зависящие от состояния. ref Root указывает на видимый элемент управления; inputRef указывает на нативный input. Ссылка части указывает на её отображаемый элемент. Передайте nativeButton вместе с render={<button />}, когда заменяете Root кнопкой. Свойства внешнего вида относятся к Root; явные классы и стили объединяются со значениями по умолчанию. Indicator получает состояния установки и неопределённости, включая состояние перехода. Установите keepMounted, чтобы сохранять неустановленный индикатор в DOM; стилизация по умолчанию скрывает его с помощью opacity. Переопределите его style или className для пользовательских переходов. Вызываемая сборка и её тип CheckboxProps по-прежнему поддерживаются. Замените сборку на Root и его часть при предоставлении пользовательских значков вместо добавления другой части к дочерним элементам сборки. Для сброса управляемой формы обработайте onReset формы и восстановите checked до начального значения. Base UI 1.8 не восстанавливает состояние неуправляемого компонента при нативном сбросе формы. required, form, value и uncheckedValue сохраняют вышестоящее поведение нативного input.

Свойства

Справочник создан на основе общедоступных типов компонента. Нативные атрибуты, включая доступные имена и обработчики событий, также поддерживаются для частей, отрисовывающих элементы.
boolean
Whether the checkbox is currently ticked.To render an uncontrolled checkbox, use the defaultChecked prop instead.
string | ((state: CheckboxRootState) => string | undefined)
CSS class applied to the element, or a function that returns a class based on the component’s state.
"accent" | "success" | "warning"
по умолчанию:"accent"
Color used while the checkbox is checked or indeterminate.
boolean
по умолчанию:"false"
Whether the checkbox is initially ticked.To render a controlled checkbox, use the checked prop instead.
boolean
по умолчанию:"false"
Whether the component should ignore user interaction.
string
Identifies the form that owns the hidden input. Useful when the checkbox is rendered outside the form.
boolean
по умолчанию:"true"
Adds padding and a hover background around the box.
string
The id of the input element.
boolean
по умолчанию:"false"
Whether the checkbox is in a mixed state: neither ticked, nor unticked.
Ref<HTMLInputElement>
A ref to access the hidden <input> element.
string
Identifies the field when a form is submitted.
boolean
по умолчанию:"false"
Whether the component renders a native <button> element when replacing it via the render prop. Set to true if the rendered element is a native button.
((checked: boolean, eventDetails: { reason: "none"; event: Event; cancel: () => void; allowPropagation: () => void; isCanceled: boolean; isPropagationAllowed: boolean; trigger: Element | undefined; }) => void)
Event handler called when the checkbox is ticked or unticked.
boolean
по умолчанию:"false"
Whether the checkbox controls a group of child checkboxes.Must be used in a Checkbox Group.
boolean
по умолчанию:"false"
Whether the user should be unable to tick or untick the checkbox.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, CheckboxRootState>
Allows you to replace the component’s HTML element with a different tag, or compose it with another component.Accepts a ReactElement or a function that returns the element to render.
boolean
по умолчанию:"false"
Whether the user must tick the checkbox before submitting a form.
"round" | "square"
по умолчанию:"square"
Corner shape of the box.
"md" | "sm"
по умолчанию:"sm"
Visual size of the checkbox.
CSSProperties | ((state: CheckboxRootState) => CSSProperties | undefined)
Style applied to the element, or a function that returns a style object based on the component’s state.
string
The value submitted with the form when the checkbox is unchecked. By default, unchecked checkboxes do not submit any value, matching native checkbox behavior.
string
The checkbox’s value. Identifies it within a Checkbox Group, falling back to name when omitted. When submitting a form, a checked box submits value; with no value, it submits the native “on”.
"outline" | "soft" | "solid"
по умолчанию:"solid"
Visual style of the box: filled, outlined, or tinted.

Checkbox.Root

boolean
Whether the checkbox is currently ticked.To render an uncontrolled checkbox, use the defaultChecked prop instead.
string | ((state: CheckboxRootState) => string | undefined)
CSS class applied to the element, or a function that returns a class based on the component’s state.
"accent" | "success" | "warning"
по умолчанию:"accent"
Color used while the checkbox is checked or indeterminate.
boolean
по умолчанию:"false"
Whether the checkbox is initially ticked.To render a controlled checkbox, use the checked prop instead.
boolean
по умолчанию:"false"
Whether the component should ignore user interaction.
string
Identifies the form that owns the hidden input. Useful when the checkbox is rendered outside the form.
boolean
по умолчанию:"true"
Adds padding and a hover background around the box.
string
The id of the input element.
boolean
по умолчанию:"false"
Whether the checkbox is in a mixed state: neither ticked, nor unticked.
Ref<HTMLInputElement>
A ref to access the hidden <input> element.
string
Identifies the field when a form is submitted.
boolean
по умолчанию:"false"
Whether the component renders a native <button> element when replacing it via the render prop. Set to true if the rendered element is a native button.
((checked: boolean, eventDetails: { reason: "none"; event: Event; cancel: () => void; allowPropagation: () => void; isCanceled: boolean; isPropagationAllowed: boolean; trigger: Element | undefined; }) => void)
Event handler called when the checkbox is ticked or unticked.
boolean
по умолчанию:"false"
Whether the checkbox controls a group of child checkboxes.Must be used in a Checkbox Group.
boolean
по умолчанию:"false"
Whether the user should be unable to tick or untick the checkbox.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, CheckboxRootState>
Allows you to replace the component’s HTML element with a different tag, or compose it with another component.Accepts a ReactElement or a function that returns the element to render.
boolean
по умолчанию:"false"
Whether the user must tick the checkbox before submitting a form.
"round" | "square"
по умолчанию:"square"
Corner shape of the box.
"md" | "sm"
по умолчанию:"sm"
Visual size of the checkbox.
CSSProperties | ((state: CheckboxRootState) => CSSProperties | undefined)
Style applied to the element, or a function that returns a style object based on the component’s state.
string
The value submitted with the form when the checkbox is unchecked. By default, unchecked checkboxes do not submit any value, matching native checkbox behavior.
string
The checkbox’s value. Identifies it within a Checkbox Group, falling back to name when omitted. When submitting a form, a checked box submits value; with no value, it submits the native “on”.
"outline" | "soft" | "solid"
по умолчанию:"solid"
Visual style of the box: filled, outlined, or tinted.

Checkbox.Indicator

string | ((state: CheckboxIndicatorState) => string | undefined)
CSS class applied to the element, or a function that returns a class based on the component’s state.
boolean
по умолчанию:"false"
Whether to keep the element in the DOM when the checkbox is not checked.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, CheckboxIndicatorState>
Allows you to replace the component’s HTML element with a different tag, or compose it with another component.Accepts a ReactElement or a function that returns the element to render.
CSSProperties | ((state: CheckboxIndicatorState) => CSSProperties | undefined)
Style applied to the element, or a function that returns a style object based on the component’s state.