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

Обзор

Используйте Switch для настройки включения или выключения. Добавьте элементу управления видимую метку или доступное имя.

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

Неконтролируемое состояние

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

Варианты внешнего вида

Сравните два размера во включенном, выключенном, отключенном, доступном только для чтения и сфокусированном состояниях. Используйте включенные примеры, чтобы попробовать переключение.

Контролируемое состояние

Передайте checked и обновляйте его с помощью onCheckedChange, чтобы управлять тем же предпочтением в состоянии React.
onCheckedChange получает следующее булево значение и сведения о событии. Свойство size принимает sm или md; по умолчанию используется md. Для единообразной полноширинной строки со значком, описанием и переключателем используйте SettingsRow.

Клавиатура и формы

Клавиша Tab переводит фокус на переключатель; клавиша Space переключает его. Щелчок по связанной с ним метке также переключает его. Используйте disabled, чтобы запретить взаимодействие, или readOnly, чтобы сохранить доступный для фокусировки элемент управления, значение которого нельзя изменить. Именованный переключатель отправляет своё значение, когда включён. Используйте value, чтобы настроить это значение, и uncheckedValue, если форма также должна отправлять значение, когда переключатель выключен.

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

Switch собирает стилизованный корневой элемент и его бегунок по умолчанию. Используйте Switch.Root с Switch.Thumb, чтобы управлять содержимым бегунка. Root управляет состоянием и внешним видом дорожки; Thumb отображает предоставленное вами содержимое.
SwitchRootProps и SwitchThumbProps — это публичные типы, экспортируемые из twenty-ui/primitives/input. Обе части принимают нативные атрибуты, обработчики, ссылки, render и зависящие от состояния обратные вызовы className и style. ref Root указывает на видимый элемент управления; inputRef указывает на нативный ввод. Ссылка части указывает на отображаемый ею элемент. Передайте nativeButton с render={<button />}, когда заменяете Root кнопкой. Свойства внешнего вида относятся к Root; явные классы и стили объединяются со значениями по умолчанию. Thumb получает текущее состояние checked, disabled, readOnly, required и Field. Его положение следует направлению чтения. Вызываемая сборка и её тип SwitchProps по-прежнему поддерживаются. Замените сборку на Root и его часть, когда предоставляете пользовательское содержимое бегунка, вместо добавления другой части к дочерним элементам сборки. Для сброса управляемой формы обработайте onReset формы и восстановите checked до исходного значения. Base UI 1.8 не восстанавливает состояние неуправляемого компонента при нативном сбросе формы. required, form, value и uncheckedValue сохраняют исходное поведение нативного ввода.

Свойства

Справочник включает свойства Base UI, специфичные для компонента и унаследованные. Также поддерживаются нативные атрибуты, такие как aria-label и data-*.
boolean
Whether the switch is currently active.To render an uncontrolled switch, use the defaultChecked prop instead.
string | ((state: SwitchRootState) => string | undefined)
CSS class applied to the element, or a function that returns a class based on the component’s state.
boolean
по умолчанию:"false"
Whether the switch is initially active.To render a controlled switch, 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 switch is rendered outside the form.
string
The id of the hidden input element.When nativeButton is true, the id is applied to the root element.
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 switch is activated or deactivated.
boolean
по умолчанию:"false"
Whether the user should be unable to activate or deactivate the switch.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, SwitchRootState>
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 activate the switch before submitting a form.
"md" | "sm"
по умолчанию:"md"
Visual size of the switch.
CSSProperties | ((state: SwitchRootState) => 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 switch is off. By default, unchecked switches do not submit any value, matching native checkbox behavior.
string
The value submitted with the form when the switch is on. By default, switch submits the “on” value, matching native checkbox behavior.

Switch.Root

boolean
Whether the switch is currently active.To render an uncontrolled switch, use the defaultChecked prop instead.
string | ((state: SwitchRootState) => string | undefined)
CSS class applied to the element, or a function that returns a class based on the component’s state.
boolean
по умолчанию:"false"
Whether the switch is initially active.To render a controlled switch, 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 switch is rendered outside the form.
string
The id of the hidden input element.When nativeButton is true, the id is applied to the root element.
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 switch is activated or deactivated.
boolean
по умолчанию:"false"
Whether the user should be unable to activate or deactivate the switch.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, SwitchRootState>
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 activate the switch before submitting a form.
"md" | "sm"
по умолчанию:"md"
Visual size of the switch.
CSSProperties | ((state: SwitchRootState) => 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 switch is off. By default, unchecked switches do not submit any value, matching native checkbox behavior.
string
The value submitted with the form when the switch is on. By default, switch submits the “on” value, matching native checkbox behavior.

Switch.Thumb

string | ((state: SwitchThumbState) => string | undefined)
CSS class applied to the element, or a function that returns a class based on the component’s state.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, SwitchThumbState>
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: SwitchThumbState) => CSSProperties | undefined)
Style applied to the element, or a function that returns a style object based on the component’s state.