首页 > 解决方案 > 如何知道在reactjs中选择了哪个“子”复选框

问题描述

我是 React 的新手,我希望这听起来不愚蠢。这里有一点上下文:我有一个ExerciseCard带有复选框的组件(和其他东西),这个组件在内部呈现CreateNewWorkout,在这里我从 API 获取数据,所以现在我想获取所有ExerciseCard具有其复选框的组件在具有该组件名称的列表中选择(在状态下它称为“名称”,在 api 中称为“exerciseName”)。

这是我的
代码CreateComponent

import React from "react";
import ExerciseCard from "../component/ExerciseCard";
import { Row } from "antd";

import WorkoutModal from "../component/WorkoutModal";

class CreateNewWorkout extends React.Component {
  constructor(props) {
    super(props);
    this.state = {};
    this.changed = this.changed.bind(this);
  }
  // this is the onChange event handlet
  changed = (e) => {
    console.log(e.target.checked);
  };
  async componentDidMount() {
    let response = await fetch("http://localhost:1337/calisthenics-exercices");

    const data = await response.json();
    // i used "objecto" to store an array of objects in state later
    const objecto = [];

    data.map((item) =>
      objecto.push({
        id: item.id,
        name: item.exerciceName,
        discription: item.discription,
        //  the json file has another object file called 'type' inside it for every item
        type: item.type.type,
        imageURL: item.imgURL,
        youtubeURL: item.youtubeURL,
      })
    );
    this.setState(objecto);
  }

  render() {
    return (
      <>
        <div
          style={{
            position: "fixed",
            bottom: 0,
            zIndex: 2,
          }}
        >
          <WorkoutModal></WorkoutModal>
        </div>
        <Row>
          {Object.entries(this.state).map((item) => (
            <ExerciseCard
              title={item[1].name}
              type={item[1].type}
              key={item}
              description={item[1].discription}
              // image={item[1].imageURL}
              youtubeURL={item[1].youtubeURL}
              //changed for onChange event
              changed={this.changed}
            ></ExerciseCard>
          ))}{" "}
          }
        </Row>
        {console.log(this.state)}
      </>
    );
  }
}

export default CreateNewWorkout;

如果ExerciseCard你需要它

import React from "react";
import { Col } from "antd";

import ExerciseModal from "./ExerciseModal";
import { Card, Tag, Checkbox } from "antd";
//import Title from "antd/lib/skeleton/Title";
//import { formatCountdown } from "antd/lib/statistic/utils";

const { Meta } = Card;
function ExerciseCard(props) {
  function tagColor() {
    switch (props.type) {
      case "core":
        return "magenta";
      case "lower body":
        return "volcano";
      case "horizontal push":
        return "cyan";
      case "horizontal pull":
        return "blue";
      case "vertical pull":
        return "geekblue";
      case "vertical push":
        return "purple";
      default:
        return "black";
    }
  }

  return (
    <Col xs={12} sm={8} md={6} lg={4}>
      <Card>
        <Meta title={props.title} />

        <Tag
          style={{ position: "absolute", top: 0, left: 0 }}
          color={tagColor()}
        >
          {props.type}
        </Tag>

        <Checkbox
          onChange={props.changed}
          style={{
            padding: "20px 0 0 0",
          }}
        ></Checkbox>
        <ExerciseModal
          title={props.title}
          description={props.description}
          youtubeURL={props.youtubeURL}
        ></ExerciseModal>
      </Card>
    </Col>
  );
}

export default ExerciseCard;


标签: reactjsevent-handlingreact-state-management

解决方案


您可以访问复选框,使用e.target 如果您需要特定的用户定义数据(例如 id、name 或其他内容,您可以将change函数定义如下:

 changed = (e, title) => {
    console.log(e.target.checked);
  };

请注意,您已经将函数定义为,arrow function并且不必this在构造函数中绑定。

然后将函数传递给ExcerciseCard您现在执行的相同方式。最后按如下方式调用函数:

 <Checkbox
          onChange={e => props.changed(e, props.title)}
          style={{
            padding: "20px 0 0 0",
          }}
        ></Checkbox>

我用 编写了一个示例title,但可以随意更改它,以便满足您的需求。


推荐阅读