使用 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>
);
};
看起來像這樣:

uj5u.com熱心網友回復:
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>
);
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/451155.html
