我在我的小型项目中创建了多个复选框。我在给复选标记的同时检索复选框的信息时遇到问题。如果我在玩具上打上勾号,则该值应为toys,或者如果我在toyslights上打勾,则应该在控制台中同时获得玩具和灯光。

这是代码:

import React from "react";
import { render } from "react-dom";
import { Segment, Form, Checkbox, Button } from "semantic-ui-react";
import axios from "axios";
export default class ShowForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      event: ""
    };
  }
  handleCheck = event => {
    console.log("Hello", event);
  };
  render() {
    return (
      <div>
        <Segment>
          <Form>
            <Checkbox label="Cake" onChange={this.handleCheck} />
            <br />
            <Checkbox label="Lights" onChange={this.handleCheck} />
            <br />
            <Checkbox label="Flowers" onChange={this.handleCheck} />
            <br />
            <Checkbox label="Toys" onChange={this.handleCheck} />
            <br />
            <Button onClick={this.handleSubmit}> Submit </Button>
          </Form>
        </Segment>
      </div>
    );
  }
}



这是完整的代码:“ https://codesandbox.io/s/zealous-paper-p9zb5

谁能帮我解决这个问题?

最佳答案

您需要一个数组来存储所有检查的状态。

handleCheck = id => () => {                      // Get indentify from each element
  const { checkedList } = this.state;
  const result = checkedList.includes(id)        // Check if checked at this moment
    ? checkedList.filter(x => x !== id)          // If checked, remove
    : [...checkedList, id];                      // If not, add
  this.setState({ checkedList: result }, () => { // setState
    console.log(this.state.checkedList);         // setState is async, log in callback
  });
};


并且,如果需要,可以将Checkbox组件设为通用组件,这样就不必将label分别绑定在三个地方。

<Checkbox
  label="Cake"
  onChange={this.handleCheck("Cake")}
  checked={checkedList.includes("Cake")}   // If included, checked
/>




另一个最小的可复制演示

在文本中尝试:



const list = [...Array(10).keys()].map(x => ({ id: x }));
const App = () => {
  const [selected, setSelected] = React.useState([]);
  const onChangeHandler = id => () => {
    selected.includes(id)
      ? setSelected(selected.filter(x => x !== id))
      : setSelected([...selected, id]);
  };
  const onRemove = () => {
    setSelected([]);
  };
  return (
    <div className="App">
      {list.map(item => (
        <input
          type="checkbox"
          key={item.id}
          checked={selected.includes(item.id)}
          onChange={onChangeHandler(item.id)}
        />
      ))}
      <br />
      <button onClick={onRemove}>Remove all</button>
      <div>{selected.join(",")}</div>
    </div>
  );
}
ReactDOM.render(<App />, document.getElementById("root"));

<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.12.0/umd/react-dom.production.min.js"></script>

09-28 03:33
查看更多