选择其他分组单选按钮时如何取消原有选中项?React+Material UI实现咨询
解决方案
你当前的两个RadioGroup为独立的非受控组件,各自维护内部选中状态,因此跨分组无法联动。只需将选中状态提升到父组件统一管理,让两个RadioGroup共享同一份受控状态即可实现需求,修改后的完整代码如下:
import * as React from 'react'; import PropTypes from 'prop-types'; import { styled } from '@mui/material/styles'; import RadioGroup, { useRadioGroup } from '@mui/material/RadioGroup'; import FormControlLabel from '@mui/material/FormControlLabel'; import Radio from '@mui/material/Radio'; const StyledFormControlLabel = styled((props) => <FormControlLabel {...props} />)( ({ theme, checked }) => ({ '.MuiFormControlLabel-label': checked && { color: theme.palette.primary.main, }, }), ); function MyFormControlLabel(props) { const radioGroup = useRadioGroup(); let checked = false; if (radioGroup) { checked = radioGroup.value === props.value; } return <StyledFormControlLabel checked={checked} {...props} />; } MyFormControlLabel.propTypes = { /** * The value of the component. */ value: PropTypes.any, }; export default function UseRadioGroup() { // 全局统一管理所有单选按钮的选中值 const [selectedValue, setSelectedValue] = React.useState('first'); return ( <> <p>group A</p> <RadioGroup name="use-radio-group" value={selectedValue} onChange={(e) => setSelectedValue(e.target.value)} > <MyFormControlLabel value="first" label="First" control={<Radio />} /> <MyFormControlLabel value="second" label="Second" control={<Radio />} /> </RadioGroup> <p>group B </p> <RadioGroup name="use-radio-group" value={selectedValue} onChange={(e) => setSelectedValue(e.target.value)} > <MyFormControlLabel value="three" label="three" control={<Radio />} /> <MyFormControlLabel value="four" label="four" control={<Radio />} /> </RadioGroup> </> ); }
修改说明
- 新增
useState钩子在父组件存储全局选中状态 - 两个RadioGroup都绑定相同的
value和onChange属性,转为受控组件 - 删除原组件的
defaultValue属性,避免受控、非受控模式混用引发异常
内容的提问来源于stack exchange,提问作者madhu malli
相关产品推荐
相关产品推荐

