使用 Material UI 取消选中单选按钮

Jac*_*cki 8 radio-button reactjs material-ui

我希望能够取消选中单选按钮,想法是这样的:如果我点击某个单选按钮,它将被选中,如果我点击另一个字段,这个另一个字段将被选中但是如果我点击在已选中的字段上,我希望取消选中它,以便所有字段都为空。我试图抓住被选中或取消选中的时刻,但似乎与复选框相反,单选按钮没有这个字段。有谁知道如何实现这一目标?

setTests = (key, e) => {
    console.log(e.checked)
    if (e.checked) {
      // this.setState({[key]: null})
      console.log('works')
    }
  }
RadioGroup
            value={this.state.test_mode}
            style={{ display: "block" }}
            onChange={e => this.setTests({ "test_mode", e.target })}
          >
            <FormControlLabel value="before" control={<Radio color="primary"/>} label="before tests" />
            <FormControlLabel value="progressing" control={<Radio color="primary"/>} label="progressing" />
            <FormControlLabel value="done" control={<Radio color="primary"/>} label="done" />

          </RadioGroup>
Run Code Online (Sandbox Code Playgroud)

Rya*_*ell 10

下面是如何执行此操作的示例。您不使用 的onChange,而是RadioGroup使用 的onClick事件Radio。如果新值与 state 中的当前值匹配,则将该值设置为空字符串。

import React from "react";
import { makeStyles } from "@material-ui/core/styles";
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";

const useStyles = makeStyles(theme => ({
  root: {
    display: "flex"
  },
  formControl: {
    margin: theme.spacing(3)
  },
  group: {
    margin: theme.spacing(1, 0)
  }
}));

export default function RadioButtonsGroup() {
  const classes = useStyles();
  const [value, setValue] = React.useState("female");

  function handleClick(event) {
    if (event.target.value === value) {
      setValue("");
    } else {
      setValue(event.target.value);
    }
  }

  return (
    <div className={classes.root}>
      <FormControl component="fieldset" className={classes.formControl}>
        <FormLabel component="legend">Gender</FormLabel>
        <RadioGroup
          aria-label="gender"
          name="gender1"
          className={classes.group}
          value={value}
        >
          <FormControlLabel
            value="female"
            control={<Radio onClick={handleClick} />}
            label="Female"
          />
          <FormControlLabel
            value="male"
            control={<Radio onClick={handleClick} />}
            label="Male"
          />
          <FormControlLabel
            value="other"
            control={<Radio onClick={handleClick} />}
            label="Other"
          />
        </RadioGroup>
      </FormControl>
    </div>
  );
}
Run Code Online (Sandbox Code Playgroud)

编辑取消选中收音机