首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在reactjs (材料表)中检查单个复选框的状态

如何在reactjs (材料表)中检查单个复选框的状态
EN

Stack Overflow用户
提问于 2021-12-09 02:09:37
回答 2查看 599关注 0票数 3

我有一个表格,其中将包含从数据库中获取的学生名单。当我单击每个学生行时,将显示一个模式弹出,其中包含4行3列的另一个表。模型中的每一列都将包含4个复选框。当我单击复选框时,我希望将该行的status列从“未决”更改为“paid”,并将徽章属性类型从“危险”更改为“成功”。问题是,当我单击复选框时,它会将所有列状态从“挂起”更改为“支付”,而不是只更改单个行。

这是我的密码

代码语言:javascript
复制
import {
  Table,
  TableBody,
  TableCell,
  Badge,
  TableFooter,
  TableRow,
  TableHeader,
  TableContainer,
  Input,
  Modal,
  ModalHeader,
  ModalBody,
  ModalFooter,
  Button,
} from "@windmill/react-ui";
import MaterialTable from "material-table";
import AddBox from "@material-ui/icons/AddBox";
import ArrowDownward from "@material-ui/icons/ArrowDownward";
import Check from "@material-ui/icons/Check";
import ChevronLeft from "@material-ui/icons/ChevronLeft";
import ChevronRight from "@material-ui/icons/ChevronRight";
import Clear from "@material-ui/icons/Clear";
import DeleteOutline from "@material-ui/icons/DeleteOutline";
import Edit from "@material-ui/icons/Edit";
import FilterList from "@material-ui/icons/FilterList";
import FirstPage from "@material-ui/icons/FirstPage";
import LastPage from "@material-ui/icons/LastPage";
import Remove from "@material-ui/icons/Remove";
import SaveAlt from "@material-ui/icons/SaveAlt";

import Search from "@material-ui/icons/Search";
import ViewColumn from "@material-ui/icons/ViewColumn";
import React, { forwardRef, useState } from "react";
const Admin = () => {
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [id, setId] = useState("");

  function openModal(ids) {
    setId(ids.studentId);
    setIsModalOpen(true);
  }
  function closeModal() {
    setIsModalOpen(false);
  }

  const tableIcons = {
    Add: forwardRef((props, ref) => <AddBox {...props} ref={ref} />),
    Check: forwardRef((props, ref) => <Check {...props} ref={ref} />),
    Clear: forwardRef((props, ref) => <Clear {...props} ref={ref} />),
    Delete: forwardRef((props, ref) => <DeleteOutline {...props} ref={ref} />),
    DetailPanel: forwardRef((props, ref) => (
      <ChevronRight {...props} ref={ref} />
    )),
    Edit: forwardRef((props, ref) => <Edit {...props} ref={ref} />),
    Export: forwardRef((props, ref) => <SaveAlt {...props} ref={ref} />),
    Filter: forwardRef((props, ref) => <FilterList {...props} ref={ref} />),
    FirstPage: forwardRef((props, ref) => <FirstPage {...props} ref={ref} />),
    LastPage: forwardRef((props, ref) => <LastPage {...props} ref={ref} />),
    NextPage: forwardRef((props, ref) => <ChevronRight {...props} ref={ref} />),
    PreviousPage: forwardRef((props, ref) => (
      <ChevronLeft {...props} ref={ref} />
    )),
    ResetSearch: forwardRef((props, ref) => <Clear {...props} ref={ref} />),
    Search: forwardRef((props, ref) => <Search {...props} ref={ref} />),
    SortArrow: forwardRef((props, ref) => (
      <ArrowDownward {...props} ref={ref} />
    )),
    ThirdStateCheck: forwardRef((props, ref) => (
      <Remove {...props} ref={ref} />
    )),
    ViewColumn: forwardRef((props, ref) => <ViewColumn {...props} ref={ref} />),
  };
  const [status, setStatus] = useState("pending");
  const [badge, setBadge] = useState("danger");

  const handleClick = (e) => {
    //Do something if checkbox is clicked
    if (e.target.checked) {
      setStatus("paid");
      setBadge("success");
    } else {
      setStatus("pending");
      setBadge("danger");
    }
  };

  // Table to be rendered in the modal
  function renderTable() {
    return (
      <TableContainer>
        <Table>
          <TableHeader>
            <TableRow>
              <TableCell>Dues</TableCell>
              <TableCell>Amount</TableCell>
              <TableCell>Status</TableCell>
            </TableRow>
          </TableHeader>
          <TableBody>
            <TableRow>
              <TableCell>
                <div className='flex items-center text-sm'>
                  <span className='font-semibold ml-2'>Level 100</span>
                </div>
              </TableCell>
              <TableCell>
                <span className='text-sm'>100</span>
              </TableCell>
              <TableCell>
                <Badge type={badge}>{status}</Badge>
                <Input
                  type='checkbox'
                  className='ml-6'
                  onClick={(e) => handleClick(e)}
                />
              </TableCell>
            </TableRow>
            <TableRow>
              <TableCell>
                <div className='flex items-center text-sm'>
                  <span className='font-semibold ml-2'>Level 200</span>
                </div>
              </TableCell>
              <TableCell>
                <span className='text-sm'>100</span>
              </TableCell>
              <TableCell>
                <Badge type={badge}>{status}</Badge>
                <Input
                  type='checkbox'
                  className='ml-6'
                  onClick={(e) => handleClick(e)}
                />
              </TableCell>
            </TableRow>
            <TableRow>
              <TableCell>
                <div className='flex items-center text-sm'>
                  <span className='font-semibold ml-2'>Level 300</span>
                </div>
              </TableCell>
              <TableCell>
                <span className='text-sm'>100</span>
              </TableCell>
              <TableCell>
                <Badge type={badge}>{status}</Badge>
                <Input
                  type='checkbox'
                  className='ml-6'
                  onClick={(e) => handleClick(e)}
                />
              </TableCell>
            </TableRow>
            <TableRow>
              <TableCell>
                <div className='flex items-center text-sm'>
                  <span className='font-semibold ml-2'>Level 400</span>
                </div>
              </TableCell>
              <TableCell>
                <span className='text-sm'>100</span>
              </TableCell>
              <TableCell>
                <Badge type={badge}>{status}</Badge>
                <Input
                  type='checkbox'
                  className='ml-6'
                  onClick={(e) => handleClick(e)}
                />
              </TableCell>
            </TableRow>
          </TableBody>
        </Table>
        <TableFooter></TableFooter>
      </TableContainer>
    );
  }

  return (
    <React.Fragment>
      {/* Modal popup */}
      <Modal isOpen={isModalOpen} onClose={closeModal}>
        <ModalHeader>{id}</ModalHeader>
        <ModalBody>{renderTable()}</ModalBody>
        <ModalFooter>
          <Button
            className='w-full sm:w-auto'
            layout='outline'
            onClick={closeModal}>
            Cancel
          </Button>
          <Button className='w-full sm:w-auto'>Accept</Button>
        </ModalFooter>
      </Modal>

      <MaterialTable
        icons={tableIcons}
        columns={[
          { title: "Student ID", field: "studentId" },
          { title: "Level", field: "level" },
          { title: "Programme", field: "programme" },
        ]}
        data={[
          {
            studentId: "UG0222021",
            level: "200",
            programme: "BCOM",
          },
          {
            studentId: "UG0199821",
            level: "200",
            programme: "BCOM",
          },
        ]}
        title='Students Information'
        onRowClick={(event, rowData) => openModal(rowData)}
      />
    </React.Fragment>
  );
};
export default Admin;
EN

回答 2

Stack Overflow用户

发布于 2021-12-13 14:31:00

这是一种更通用的方法,我冒昧地使用了打字稿,因为这样可以更容易地显示正在发生的事情。

代码语言:javascript
复制
 const initialStatuses = {
  inputLevel100: "pending",
  inputLevel200: "pending",
  inputLevel300: "pending",
  inputLevel400: "pending",
 }

 const initialBadges = {
  inputLevel100: "danger",
  inputLevel200: "danger",
  inputLevel300: "danger",
  inputLevel400: "danger",
 }

 const [status, setStatus] = React.useState<{ [key: string]: string }>(initialBadges);
 const [badge, setBadge] = React.useState<{ [key: string]: string }>(initialStatuses);

 const handleClick = (e: { target: { checked: boolean; name: string} }) => {
 const name = e.target.name;

 if (e.target.checked) {
  setBadge({
    ...badge,
    [name]: "success",
  });
  
  setStatus({
   ...status,
   [name]: "paid",
  });
 }  

}; 

只要简单地说,你就可以得到身份或徽章的价值。

代码语言:javascript
复制
status["Level200"] // Should return either "pending" or "paid"

代码语言:javascript
复制
badge["Level200"] // Should return either "danger" or "success"

这应该是非常有表现力的(请参阅Performance of key lookup in JavaScript object了解更多信息)

但是,更重要的是,您现在有了一种通用的方法,可以添加更多的状态和徽章,而不必担心为每个新添加的状态或徽章添加useState

另外,这种方法的另一个优点是,您可以(比方说)从远程api获取状态和徽章列表,或者(比方说)有一个statuses.js文件,其中包含一个状态列表&客户端的一个badges.js文件,然后您可以映射它。这样,您的代码就更容易扩展,移除/添加新的状态和标记变得非常简单。

票数 1
EN

Stack Overflow用户

发布于 2021-12-12 09:47:57

这仅仅是因为你在所有的状态徽章上使用一个州。你应该用不同的州来管理每一个徽章。您可以将name属性添加到每个输入中,这样您就可以看到哪个输入正在handleClick函数中更改,然后更新相关的状态。您可以添加以下代码:

代码语言:javascript
复制
/* states */
const[statusOfLevel100, setStatusOfLevel100] = useState('pending')
const[statusOfLevel200, setStatusOfLevel200] = useState('pending')
const[statusOfLevel300, setStatusOfLevel300] = useState('pending')
const[statusOfLevel400, setStatusOfLevel400] = useState('pending')
const[badgeOfLevel100, setBadgeOfLevel100] = useState('danger')
const[badgeOfLevel200, setBadgeOfLevel200] = useState('danger')
const[badgeOfLevel300, setBadgeOfLevel300] = useState('danger')
const[badgeOfLevel400, setBadgeOfLevel400] = useState('danger')
...
/* handleClick function */
const handleClick = (e) => {
switch (e.target.name) {
  case 'inputLevel100':
    if(e.target.checked) {
      setStatusOfLevel100('paid')
      setBadgeOfLevel100('success')
    } else {
      setStatusOfLevel100('pending')
      setBadgeOfLevel100('danger')
    }
    break;
case 'inputLevel200':
    if(e.target.checked) {
      setStatusOfLevel200('paid')
      setBadgeOfLevel200('success')
    } else {
      setStatusOfLevel200('pending')
      setBadgeOfLevel200('danger')
    }
    break;
case 'inputLevel300':
    if(e.target.checked) {
      setStatusOfLevel300('paid')
      setBadgeOfLevel300('success')
    } else {
      setStatusOfLevel300('pending')
      setBadgeOfLevel300('danger')
    }
    break;
case 'inputLevel400':
    if(e.target.checked) {
      setStatusOfLevel400('paid')
      setBadgeOfLevel400('success')
    } else {
      setStatusOfLevel400('pending')
      setBadgeOfLevel400('danger')
    }
    break;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70283927

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档