在反应中一次切换一个复选框

发布于 2025-01-10 20:35:41 字数 1611 浏览 0 评论 0原文

我有一个渲染材质 UI 表的 React 组件。该表填充有从 API 获取的数据。在其中一个表格单元格中,我有一个 Material UI 开关,用于切换用户是被阻止还是处于活动状态。然而,每当我检查其中一个开关时,所有开关都会同时被检查,这不是我想要实现的目标。我希望能够单独检查每个开关,而不影响其他开关的状态。有什么好方法可以完成这个任务吗?

下面是示例代码片段:

    const Customers = ({customers}) => {
        const [checked, setChecked] = useState(false);

        const handleSwitchChange = (event) => {
        setChecked(event.target.checked);
    }
        return customers.map((customer) => {
    const {_id, name, email, } = customer;
    return (
      <TableRow hover role="checkbox" tabIndex={-1} key={_id}>
        <TableCell style={{ minWidth: 150 }}>{name}</TableCell>
        <TableCell>{email}</TableCell>
        <TableCell>Activated</TableCell>
        <TableCell align="center">
          <Switch
            color="error"
            onChange={handleSwitchChange}
            checked={checked}
          />
        </TableCell>
        <TableCell>
          <CustomIconButton
            startIcon={<VisibilitySharpIcon />}
            title="Details"
          />
          <CustomIconButton
            startIcon={<EditSharpIcon />}
            title="Edit"
          />
          <CustomIconButton
            startIcon={<MailSharpIcon />}
            title="Send"
          />
          <IconButton>
            <DeleteSharpIcon />
          </IconButton>
        </TableCell>
      </TableRow>
    );
  });
}

I have a react component that renders material UI table. This table is populated with data that is fetched from an API. In one of the table cells, I have a Material UI switch for toggling whether a user is blocked or active. However, whenever I check one of the switches, all the switches simultaneously get checked which is not what I intend to achieve. I want to be able to check each switch individually without it affecting the state of the other switches. Is there a great way to get this done? Table data representation

Below is a sample code snippet:

    const Customers = ({customers}) => {
        const [checked, setChecked] = useState(false);

        const handleSwitchChange = (event) => {
        setChecked(event.target.checked);
    }
        return customers.map((customer) => {
    const {_id, name, email, } = customer;
    return (
      <TableRow hover role="checkbox" tabIndex={-1} key={_id}>
        <TableCell style={{ minWidth: 150 }}>{name}</TableCell>
        <TableCell>{email}</TableCell>
        <TableCell>Activated</TableCell>
        <TableCell align="center">
          <Switch
            color="error"
            onChange={handleSwitchChange}
            checked={checked}
          />
        </TableCell>
        <TableCell>
          <CustomIconButton
            startIcon={<VisibilitySharpIcon />}
            title="Details"
          />
          <CustomIconButton
            startIcon={<EditSharpIcon />}
            title="Edit"
          />
          <CustomIconButton
            startIcon={<MailSharpIcon />}
            title="Send"
          />
          <IconButton>
            <DeleteSharpIcon />
          </IconButton>
        </TableCell>
      </TableRow>
    );
  });
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

又爬满兰若 2025-01-17 20:35:42

你正在做的是检查变量与React功能组件相关,所以当你setChecked(true)时,你将为所有复选框设置它。

每个客户都应该有一个检查值。因此,当您处理开关时,您应该映射您的客户以找到想要的开关(使用 id,您将通过handleSwitch 函数传递它)。然后当您找到它时,您将获得一个过滤列表,然后您应该访问第一个列表(filteredList.first)。
并设置checked=!checked。
解决方案2 将索引传递给函数handleSwitch 并将customers[index].checked 设置为相反的值。

What you are doing is the checked variable is related to the React Functional Components, so when you setChecked(true) for example you will set it for all the checkboxes.

Each customer should have a checked value. so when you handle the switch you should map through your customers to find the intended one (using the id, you will passe it through the handleSwitch function). then when you find it you will get a filtered list then you should access the first one (filteredList.first).
and set checked =!checked.
Solution 2 you pass the index to the function handleSwitch and set customers[index].checked to the opposite.

无妨# 2025-01-17 20:35:42

您正在将公共选中选项传递给所有行。请将其他参数(例如 isChecked)单独传递到您的行,并通过将键传递给该函数来更改该函数上的该参数。

You are passing the common checked option to all the rows. Please pass additional parameters like isChecked indigual to your rows and change that parameter on that function by passing key to that.

痴者 2025-01-17 20:35:42

您应该创建一个单独的组件 (SwitchComp) 来隔离切换逻辑,如下所示。

import { useState } from "react";

const SwitchComp = ({ color = "error" }) => {
  const [checked, setChecked] = useState(false);

  const handleSwitchChange = (event) => {
    setChecked(event.target.checked);
  };

  return (
    <Switch color={color} onChange={handleSwitchChange} checked={checked} />
  );
};

在之前使用 Switch 组件的地方使用 SwitchComp,如下所示。

const Customers = ({ customers }) => {
  return customers.map((customer) => {
    const { _id, name, email } = customer;
    return (
      <TableRow hover role="checkbox" tabIndex={-1} key={_id}>
        <TableCell style={{ minWidth: 150 }}>{name}</TableCell>
        <TableCell>{email}</TableCell>
        <TableCell>Activated</TableCell>
        <TableCell align="center">
          <SwitchComp color="error" />
        </TableCell>
        <TableCell>
          <CustomIconButton
            startIcon={<VisibilitySharpIcon />}
            title="Details"
          />
          <CustomIconButton startIcon={<EditSharpIcon />} title="Edit" />
          <CustomIconButton startIcon={<MailSharpIcon />} title="Send" />
          <IconButton>
            <DeleteSharpIcon />
          </IconButton>
        </TableCell>
      </TableRow>
    );
  });
};

You should create a separate component (SwitchComp) to isolate the toggle logic like below.

import { useState } from "react";

const SwitchComp = ({ color = "error" }) => {
  const [checked, setChecked] = useState(false);

  const handleSwitchChange = (event) => {
    setChecked(event.target.checked);
  };

  return (
    <Switch color={color} onChange={handleSwitchChange} checked={checked} />
  );
};

Use SwitchComp where you used the Switch component previously like below.

const Customers = ({ customers }) => {
  return customers.map((customer) => {
    const { _id, name, email } = customer;
    return (
      <TableRow hover role="checkbox" tabIndex={-1} key={_id}>
        <TableCell style={{ minWidth: 150 }}>{name}</TableCell>
        <TableCell>{email}</TableCell>
        <TableCell>Activated</TableCell>
        <TableCell align="center">
          <SwitchComp color="error" />
        </TableCell>
        <TableCell>
          <CustomIconButton
            startIcon={<VisibilitySharpIcon />}
            title="Details"
          />
          <CustomIconButton startIcon={<EditSharpIcon />} title="Edit" />
          <CustomIconButton startIcon={<MailSharpIcon />} title="Send" />
          <IconButton>
            <DeleteSharpIcon />
          </IconButton>
        </TableCell>
      </TableRow>
    );
  });
};

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文