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

Обзор

Radio представляет один вариант внутри RadioGroup. Задайте для каждого варианта уникальное значение value и видимую метку. Группа управляет выбранным значением.

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

Свойство size принимает sm или md; по умолчанию используется sm. Используйте одинаковый размер для параметров в группе.

Визуальные варианты

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

Готовые компоненты

Radio.Root и Radio.Indicator предоставляют установленные части Base UI без стилизованной сборки. Комбинируйте их, когда требуется пользовательское содержимое или размещение индикатора. Вызываемый Radio предоставляет внешний вид переключателя и индикатор Twenty для распространённых вариантов.
Стандартные переключатели и Radio.Root отображают span с семантикой переключателя и расположенный рядом скрытый нативный input. Радиокнопки-карточки рендерят div. ref указывает на отрендеренный корневой элемент; inputRef указывает на поле ввода. Radio.Indicator рендерит span, и его ref указывает на этот элемент. render, зависящие от состояния className и style, нативные атрибуты и обработчики событий сохраняют свои исходные контракты. Публичные типы включают RadioProps, RadioRootProps, RadioRootState, RadioIndicatorProps и RadioIndicatorState.

Параметры карточки

Используйте variant="card" для вариантов на всю ширину со встроенным индикатором радиокнопки. По умолчанию радиокнопки-карточки сохраняют корневой div. Используйте render, чтобы явно выбрать другой элемент. Если этот элемент является нативной кнопкой, также установите nativeButton. Размещайте интерактивные элементы управления за пределами содержимого карточки. Предоставьте группе достаточно ширины для ее содержимого и оставьте место для индикатора в правом верхнем углу. Заголовок, значок и краткое описание помогают пояснить каждый вариант.

Явная нативная композиция

Ссылка ref указывает на составную кнопку. Для пользовательских корневых элементов, не являющихся кнопками, оставьте nativeButton со значением false и перенаправьте предоставленные свойства рендеринга и ref на фактический элемент.

Клавиатура и выбор

Tab позволяет войти в группу или выйти из неё. Клавиши со стрелками перемещаются между доступными параметрами и выбирают параметр в фокусе. Пробел выбирает переключатель в фокусе. Установленная радиокнопка Base UI подавляет выбор по Enter как для корневых элементов по умолчанию, так и для скомпонованных нативных кнопок. Обработчики выбора и изменения должны находиться в RadioGroup; см. его неконтролируемый пример и контролируемый пример. Стрелки радиокнопки изменяют выбор при перемещении фокуса. Dropdown.SelectionGroup перемещает фокус стрелками и подтверждает выбор клавишей Enter или Space. Radio и Radio.Root являются обобщёнными по типу значения. Согласуйте этот тип с типом его группы. Нативные атрибуты, такие как aria-describedby, могут связывать параметр с дополнительным справочным текстом.

Свойства

Справочник генерируется на основе публичных типов компонентов. Нативные атрибуты, включая доступные имена и обработчики событий, также принимаются для частей, отображающих элементы.
ReactNode
Option content. Card options wrap it in a padded full-width content area.
string | ((state: RadioRootState) => string | undefined)
CSS class applied to the element, or a function that returns a class based on the component’s state.
boolean
Whether the component should ignore user interaction.
Ref<HTMLInputElement>
A ref to access the hidden input element.
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.
boolean
Whether the user should be unable to select the radio button.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, RadioRootState>
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
Whether the user must choose a value before submitting a form.
"md" | "sm"
по умолчанию:"sm"
Visual size of the radio.
CSSProperties | ((state: RadioRootState) => CSSProperties | undefined)
Style applied to the element, or a function that returns a style object based on the component’s state.
TValue
обязательно
The unique identifying value of the radio in a group.
"card" | "default"
по умолчанию:"default"
Appearance of the styled assembly: a standard radio or a full-width card. Standard radios use a span and card radios use a div unless render replaces the root.

Radio.Root

string | ((state: RadioRootState) => string | undefined)
CSS class applied to the element, or a function that returns a class based on the component’s state.
boolean
Whether the component should ignore user interaction.
Ref<HTMLInputElement>
A ref to access the hidden input element.
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.
boolean
Whether the user should be unable to select the radio button.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, RadioRootState>
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
Whether the user must choose a value before submitting a form.
CSSProperties | ((state: RadioRootState) => CSSProperties | undefined)
Style applied to the element, or a function that returns a style object based on the component’s state.
Value
обязательно
The unique identifying value of the radio in a group.

Radio.Indicator

string | ((state: RadioIndicatorState) => 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 HTML element in the DOM when the radio button is inactive.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, RadioIndicatorState>
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: RadioIndicatorState) => CSSProperties | undefined)
Style applied to the element, or a function that returns a style object based on the component’s state.