未默认选中Material-ui FormControlLabel

时间:2019-03-09 10:28:59

标签: reactjs radio-button material-ui

我的formcontrollabel有问题。我希望默认情况下选中单选按钮,但是属性checked似乎不起作用。

我尝试使用逻辑语句,只是将true作为参数,但似乎无济于事。有什么想法吗?

这是我的代码:

const styles = theme => ({
    root: {
        display: 'flex',
    },
    formControl: {
        margin: theme.spacing.unit * 3,
    },
    group: {
        margin: `${theme.spacing.unit}px 0`,
    },
});

class SelectPeriod extends Component {
    constructor(props) {
        super(props);
        this.state = {
            selectedValue: 'daily'
        };
    }

    handleChange = (value) => {
        this.setState({selectedValue: value});
    };

    render() {
        const { classes} = this.props;
        return (
            <div>
                <FormControl component="fieldset" className={classes.formControl}>
                    <FormLabel component="legend">Time Period</FormLabel>
                    <RadioGroup
                        aria-label="TimePeriod"
                        name="timePeriod"
                        className={classes.group}
                        value={this.state.value}
                        onChange={this.handleChange}
                    >
                        <FormControlLabel value="daily" checked control={<Radio color="primary" />} label="Daily" />
                        <FormControlLabel value="weekly" control={<Radio color="primary" />} label="Weekly" />
                        <FormControlLabel value="monthly" control={<Radio color="primary" />} label="Monthly" />
                    </RadioGroup>
                </FormControl>
            </div>
        )
    }
}
SelectPeriod.propTypes = {
    classes: PropTypes.object.isRequired,
};

export default withStyles(styles)(SelectPeriod);

1 个答案:

答案 0 :(得分:1)

  1. 在您的<RadioGroup>中,您传递了错误的状态(您定义了selectedValue,而不是value
<RadioGroup
  aria-label="TimePeriod"
  name="timePeriod"
  className={classes.group}
  value={this.state.selectedValue}
  onChange={this.handleChange}
>

(使用RadioGroup中的props值,您将控制将选择哪个无线电字段。)

  1. 我想您的handleChange函数会出现问题。只需再次检查材料ui文档。 https://material-ui.com/demos/selection-controls/