我有以下使用按钮组 Material 的 react 组件。
页面第一次渲染时,默认值5被选中,单选框显示为checked
。
但是,当我选择任何其他单选框时,所有单选框都会变黑,并且没有任何内容显示为选中状态。我已经检查并且 setValue
正在被调用并更改值,所以我不明白为什么值更改没有反射(reflect)在单选框中?
import React, {useState} from 'react';
import Radio from '@material-ui/core/Radio';
import RadioGroup from '@material-ui/core/RadioGroup';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import FormControl from '@material-ui/core/FormControl';
import FormLabel from '@material-ui/core/FormLabel';
import Typography from '@material-ui/core/Typography';
import { makeStyles } from '@material-ui/core/styles';
const useStyles = makeStyles((theme) => ({
root: {
marginTop: theme.spacing(3)
},
amountSelectGroupLabel: {
'&.MuiFormLabel-root': {
color: theme.palette.borders.primary
}
}
}));
const RadioButtons = (props) => {
const { radioButton, ...labelProps } = props;
return (
<FormControlLabel
control={<Radio color="secondary" />}
label={`$${props.value}`}
labelPlacement="bottom"
{...labelProps}
/>
)
}
function SelectTokenAmountToBuyComponent(props) {
const classes = useStyles();
const amountRanges = [1, 5, 10, 20, 50, 100];
const [value, setValue] = useState(5);
function handleChange(event) {
const {target: {value: _value}} = event;
setValue(_value);
}
return (
<FormControl className={classes.root} component="fieldset">
<FormLabel className={classes.amountSelectGroupLabel} component="legend">
<Typography gutterBottom variant='subtitle2'>
Select amount
</Typography>
<Typography variant='caption'>
($1 = 100 tokens)
</Typography>
</FormLabel>
<RadioGroup
row
name="monetaryValue"
value={value}
onChange={handleChange}>
{
amountRanges.map((amount, index) => (
<RadioButtons key={`select-amount-${amount}-tokens-${index}`} value={amount} radioButton/>
))
}
</RadioGroup>
</FormControl>
)
}
export default SelectTokenAmountToBuyComponent;
最佳答案
onChange
事件以字符串类型返回值。然后,您的 setState
会触发重新渲染并将该值分配给 RadioGroup
。它此时停止工作,因为 RadioGroup
具有例如 value={"10"}
,而相应的 RadioButtons
具有 值={10}
关于reactjs - Material ui单选按钮组在选择时不改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65702540/