Обзор
Используйте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.
Свойства
Справочник создан на основе общедоступных типов компонента. Нативные атрибуты, включая доступные имена и обработчики событий, также поддерживаются для частей, отрисовывающих элементы.Whether the checkbox is currently ticked.To render an uncontrolled checkbox, use the
defaultChecked prop instead.CSS class applied to the element, or a function that
returns a class based on the component’s state.
Color used while the checkbox is checked or indeterminate.
Whether the checkbox is initially ticked.To render a controlled checkbox, use the
checked prop instead.Identifies the form that owns the hidden input.
Useful when the checkbox is rendered outside the form.
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.
Whether the checkbox controls a group of child checkboxes.Must be used in a Checkbox Group.
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.Style applied to the element, or a function that
returns a style object based on the component’s state.
The value submitted with the form when the checkbox is unchecked.
By default, unchecked checkboxes do not submit any value, matching native checkbox behavior.
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”.Visual style of the box: filled, outlined, or tinted.
Checkbox.Root
Whether the checkbox is currently ticked.To render an uncontrolled checkbox, use the
defaultChecked prop instead.CSS class applied to the element, or a function that
returns a class based on the component’s state.
Color used while the checkbox is checked or indeterminate.
Whether the checkbox is initially ticked.To render a controlled checkbox, use the
checked prop instead.Identifies the form that owns the hidden input.
Useful when the checkbox is rendered outside the form.
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.
Whether the checkbox controls a group of child checkboxes.Must be used in a Checkbox Group.
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.Style applied to the element, or a function that
returns a style object based on the component’s state.
The value submitted with the form when the checkbox is unchecked.
By default, unchecked checkboxes do not submit any value, matching native checkbox behavior.
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”.Visual style of the box: filled, outlined, or tinted.
Checkbox.Indicator
CSS class applied to the element, or a function that
returns a class based on the component’s state.