Радиокнопка
Radio buttons allow the user to select one option from a set.
Use radio buttons when the user needs to see all available options. Если доступные параметры можно свернуть, возможно лучше использовать раскрывающееся меню, так как оно занимает меньше места.
Для радиокнопок наиболее часто используемый параметр должен быть выбран по умолчанию.
Radio group
RadioGroup
- это полезная обертка, используемая для группировки компонентов Radio
, она обеспечивает более простой API и управление с клавиатуры.
<FormControl component="fieldset">
<FormLabel component="legend">Gender</FormLabel>
<RadioGroup
aria-label="gender"
defaultValue="female"
name="radio-buttons-group"
>
<FormControlLabel value="female" control={<Radio />} label="Female" />
<FormControlLabel value="male" control={<Radio />} label="Male" />
<FormControlLabel value="other" control={<Radio />} label="Other" />
</RadioGroup>
</FormControl>
<FormControl component="fieldset">
<FormLabel component="legend">Gender</FormLabel>
<RadioGroup row aria-label="gender" name="row-radio-buttons-group">
<FormControlLabel value="female" control={<Radio />} label="Female" />
<FormControlLabel value="male" control={<Radio />} label="Male" />
<FormControlLabel value="other" control={<Radio />} label="Other" />
<FormControlLabel
value="disabled"
disabled
control={<Radio />}
label="other"
/>
</RadioGroup>
</FormControl>
<FormControl component="fieldset">
<FormLabel component="legend">Gender</FormLabel>
<RadioGroup
aria-label="gender"
name="controlled-radio-buttons-group"
value={value}
onChange={handleChange}
>
<FormControlLabel value="female" control={<Radio />} label="Female" />
<FormControlLabel value="male" control={<Radio />} label="Male" />
</RadioGroup>
</FormControl>
<Radio
checked={selectedValue === 'a'}
onChange={handleChange}
value="a"
name="radio-buttons"
inputProps={{ 'aria-label': 'A' }}
/>
<Radio
checked={selectedValue === 'b'}
onChange={handleChange}
value="b"
name="radio-buttons"
inputProps={{ 'aria-label': 'B' }}
/>
<Radio {...controlProps('a')} size="small" />
<Radio {...controlProps('b')} />
<Radio
{...controlProps('c')}
sx={{
'& .MuiSvgIcon-root': {
fontSize: 28,
},
}}
/>
<Radio {...controlProps('a')} />
<Radio {...controlProps('b')} color="secondary" />
<Radio {...controlProps('c')} color="success" />
<Radio {...controlProps('d')} color="default" />
<Radio
{...controlProps('e')}
sx={{
color: pink[800],
'&.Mui-checked': {
color: pink[600],
},
}}
/>
Расположение метки
You can change the placement of the label with the FormControlLabel
component's labelPlacement
prop:
Отображение ошибок
In general, radio buttons should have a value selected by default. If this is not the case, you can display an error if no value is selected when the form is submitted:
Customized radios
Ниже находится пример кастомизации компонента. Вы можете узнать об этом больше в документации по переопределению свойств.
<FormControl component="fieldset">
<FormLabel component="legend">Gender</FormLabel>
<RadioGroup defaultValue="female" aria-label="gender" name="customized-radios">
<FormControlLabel value="female" control={<BpRadio />} label="Female" />
<FormControlLabel value="male" control={<BpRadio />} label="Male" />
<FormControlLabel value="other" control={<BpRadio />} label="Other" />
<FormControlLabel
value="disabled"
disabled
control={<BpRadio />}
label="(Disabled option)"
/>
</RadioGroup>
</FormControl>
useRadioGroup
For advanced customization use cases, a useRadioGroup()
hook is exposed. It returns the context value of the parent radio group. The Radio component uses this hook internally.
API
<RadioButton
value="radioA"
inputProps={{ 'aria-label': 'Radio A' }}
/>
Возвращает
value
(object):
value.name
(string [optional]): The name used to reference the value of the control.value.onChange
(func [optional]): Callback fired when a radio button is selected.value.value
(any [optional]): Value of the selected radio button.
Пример
<RadioGroup name="use-radio-group" defaultValue="first">
<MyFormControlLabel value="first" label="First" control={<Radio />} />
<MyFormControlLabel value="second" label="Second" control={<Radio />} />
</RadioGroup>
Бесплатно
Доступность
(WAI-ARIA: https://www.w3.org/TR/wai-aria-practices/#radiobutton)
- Все элементы формы должны иметь метки, в том числе радиокнопки, переключатели и чекбоксы. В большинстве случаев это делается с помощью элемента
<label>
(FormControlLabel). - Когда метка не может быть использована, необходимо добавить атрибут непосредственно на поле ввода. В этом случае можно применить дополнительный атрибут (например,
aria-label
,aria-labelledby
,title
) через свойствоinputProps
.
<Radio
value="radioA"
inputProps={{
'aria-label': 'Radio A',
}}
/>