跳转到内容

Radio 单选框

用户可以通过单选按钮从一组中选择一个选项。

当用户想要看到所有的选项时,可以使用单选按钮。 如果可用选项可以折叠,请您考虑使用占用空间更少的下拉菜单。

默认情况下,单选按钮应该选择了最常用的选项。

RadioGroup

RadioGroup适用于一组Radio,它提供相对简单的 API 并且能够使用键盘对该RadioGroup 进行控制。

Gender
<FormControl component="fieldset">
  <FormLabel component="legend">Gender</FormLabel>
  <RadioGroup aria-label="gender" name="gender1" value={value} onChange={handleChange}>
    <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="(Disabled option)" />
  </RadioGroup>
</FormControl>

Standalone radio buttons

Radio can also be used standalone, without the RadioGroup wrapper.

标签放置

You can change the placement of the label with the FormControlLabel component's labelPlacement prop:

labelPlacement

Show error

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:

Pop quiz: Material-UI is...

Choose wisely

<form onSubmit={handleSubmit}>
  <FormControl component="fieldset" error={error} className={classes.formControl}>
    <FormLabel component="legend">Pop quiz: Material-UI is...</FormLabel>
    <RadioGroup aria-label="quiz" name="quiz" value={value} onChange={handleRadioChange}>
      <FormControlLabel value="best" control={<Radio />} label="The best!" />
      <FormControlLabel value="worst" control={<Radio />} label="The worst." />
    </RadioGroup>
    <FormHelperText>{helperText}</FormHelperText>
    <Button type="submit" variant="outlined" color="primary" className={classes.button}>
      Check Answer
    </Button>
  </FormControl>
</form>

自定义单选框

以下是自定义组件的一个示例。 您可以在重写文档页中了解有关此内容的更多信息。

Gender
<FormControl component="fieldset">
  <FormLabel component="legend">Gender</FormLabel>
  <RadioGroup defaultValue="female" aria-label="gender" name="customized-radios">
    <FormControlLabel value="female" control={<StyledRadio />} label="Female" />
    <FormControlLabel value="male" control={<StyledRadio />} label="Male" />
    <FormControlLabel value="other" control={<StyledRadio />} label="Other" />
    <FormControlLabel
      value="disabled"
      disabled
      control={<StyledRadio />}
      label="(Disabled option)"
    />
  </RadioGroup>
</FormControl>

什么时候使用

可访问性

(WAI-ARIA: https://www.w3.org/TR/wai-aria-practices/#radiobutton)

  • 所有表单控件都应该带有标签,而这包括了单选按钮,复选框和开关。 在大多数情况下,这是通过使用一个 <label> 元素(FormControlLabel)实现的。
  • 如果无法使用标签,您则必须在输入组件中直接添加属性。 在这种情况下,您可以经由 inputProps 属性,来附着一些额外的属性(例如 arial-labelaria-labelledbytitle)。
<RadioButton
  value="radioA"
  inputProps={{ 'aria-label': 'Radio A' }}
/>