首页 > 解决方案 > 试图选中一个复选框 选中所有复选框

问题描述

我正在尝试使用本地存储来保留复选框...应用后...如果我选择一个复选框选择所有复选框...我使用复选框的地图功能...任何人都可以帮助解决这个问题... ..我想选择单个复选框

这是 linkmof 代码沙箱: https ://codesandbox.io/s/sparkling-wind-rmz1z?file=/src/App.js

分支.js

import React, { Component } from "react";
import Checkbox from "@material-ui/core/Checkbox";
import FormGroup from "@material-ui/core/FormGroup";
import FormControlLabel from "@material-ui/core/FormControlLabel";
import { List, ListItem } from "@material-ui/core";
import Button from "react-bootstrap/Button";

// const [isChecked, setIsChecked] = useState(true);
class BranchComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      value: {},
      count: 0,
      checked: localStorage.getItem("checkbox") === "true" ? true : false
    };
  }
  CheckedBox = e => {
    let checked = e.target.checked;
    let count = this.state.count;
    if (checked) {
      console.log(checked);
      this.setState({ checked: true });
      count++;
    } else {
      count--;
      console.log(checked);
      this.setState({ checked: false });
    }
    this.setState({ count });
    console.log(count);

    let values = this.state.value;
    values[e.target.value] = e.target.checked;
    this.setState({ value: values });

    localStorage.setItem("checkbox", e.target.checked.toString());
  };

  checkBoxSubmit = e => {
    e.preventDefault();
    console.log(this.state.value);
  };
  render() {
    const arr = ["Branch 1", "Branch 2", "Branch 3"];
    return (
      <React.Fragment>
        <form onSubmit={this.checkBoxSubmit}>
          <FormGroup aria-label="position" row>
            <List className="courses-college-regis">
              {arr.map((a, key) => (
                <ListItem button key={key}>
                  <FormControlLabel
                    label={a}
                    value={a}
                    type="checkbox"
                    name={a}
                    checked={this.state.checked}
                    control={<Checkbox color="primary" />}
                    onClick={this.CheckedBox}
                  />
                </ListItem>
              ))}
            </List>
          </FormGroup>
          Count :{this.state.count}
          <br />
          <Button type="submit" variant="primary">
            Submit
          </Button>
        </form>
      </React.Fragment>
    );
  }
}

export default BranchComponent;

标签: reactjs

解决方案


我更新了你的代码工作正常,

import React, { Component } from "react";
import Checkbox from "@material-ui/core/Checkbox";
import FormGroup from "@material-ui/core/FormGroup";
import FormControlLabel from "@material-ui/core/FormControlLabel";
import { List, ListItem } from "@material-ui/core";
import Button from "react-bootstrap/Button";
var localStorageData = localStorage.getItem("checkbox");
// const [isChecked, setIsChecked] = useState(true);
class BranchComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      value: {},
      count:
        localStorageData && typeof JSON.parse(localStorageData) === "object"
          ? JSON.parse(localStorageData).length
          : 0,
      checked:
        localStorageData && typeof JSON.parse(localStorageData) === "object"
          ? JSON.parse(localStorageData)
          : []
    };
  }
  CheckedBox = (e, index) => {
    let checked = e.target.checked;
    let count = this.state.count;
    var addData = [...this.state.checked, index];
    if (checked) {
      console.log(checked);
      this.setState({ checked: [...new Set(addData)] });
      count++;
    } else {
      count--;
      console.log(checked);
      addData = addData.filter(find => find !== index);
      this.setState({ checked: addData });
    }
    this.setState({ count: addData.length });
    console.log(count);

    let values = this.state.value;
    values[e.target.value] = e.target.checked;
    this.setState({ value: values });

    localStorage.setItem("checkbox", JSON.stringify([...new Set(addData)]));
  };

  checkBoxSubmit = e => {
    e.preventDefault();
    console.log(this.state.value);
  };
  render() {
    const arr = ["Branch 1", "Branch 2", "Branch 3"];
    return (
      <React.Fragment>
        <form onSubmit={this.checkBoxSubmit}>
          <FormGroup aria-label="position" row>
            <List className="courses-college-regis">
              {arr.map((a, key) => (
                <ListItem button key={key}>
                  <FormControlLabel
                    label={a}
                    value={a}
                    type="checkbox"
                    name={a}
                    checked={this.state.checked.includes(a)}
                    control={<Checkbox color="primary" />}
                    onClick={e => this.CheckedBox(e, a)}
                  />
                </ListItem>
              ))}
            </List>
          </FormGroup>
          Count :{this.state.count}
          <br />
          <Button type="submit" variant="primary">
            Submit
          </Button>
        </form>
      </React.Fragment>
    );
  }
}

export default BranchComponent;

在此处输入图像描述

在此处输入图像描述


推荐阅读