单击按钮检查收音机或单击收音机

Check radio on button click or click on radio

使用 mui 在按钮内创建单选按钮,应该可以单击单选按钮或按钮,当单击其中任何一个时,必须选中单选按钮。只能选一个选项,要么女,要么男。

我知道我可以对点击使用多个使用状态,但是有没有更好的方法来做到这一点?

import FormControl from '@mui/material/FormControl';
import FormLabel from '@mui/material/FormLabel';
import RadioGroup from '@mui/material/RadioGroup';
import FormControlLabel from '@mui/material/FormControlLabel';
import Button from '@mui/material/Button';
import Radio from '@mui/material/Radio';

export const radioButtonGroup = () => {
  const [value, setValue] = React.useState('female');
  const [clicked, setClicked] = useState(false);

  return (
    <FormControl>
      <FormLabel>Gender</FormLabel>
      <RadioGroup value={value}>
        <Button
          onClick={() => setClicked(true)}
          variant="outlined">
        <FormControlLabel
          value="female"
          control={<Radio checked={clicked} />}
          label="Female" />
        </Button>
        <Button
          onClick={() => setClicked(true)}
          variant="outlined">
        <FormControlLabel
          value="male"
          control={<Radio checked={clicked} />}
          label="Male" />
        </Button>
      </RadioGroup>
    </FormControl>
  );
};

看起来像这样:

export const radioButtonGroup = () => {
  const [gender, setGender] = useState('');

  return (
    <FormControl>
      <FormLabel>Gender</FormLabel>
      <RadioGroup>
        <Button
          onClick={() => setGender('female')}
          variant="outlined">
        <FormControlLabel
          control={<Radio checked={gender === 'female'} />}
          label="Female" />
        </Button>
        <Button
          onClick={() => setGender('male')}
          variant="outlined">
        <FormControlLabel
          control={<Radio checked={gender === 'male'} />}
          label="Male" />
        </Button>
      </RadioGroup>
    </FormControl>
  );
};