首页 > 解决方案 > 在反应表中单独切换多个按钮

问题描述

非活动状态:
非活动状态

活动状态:
活动状态

当我切换一个按钮时,其他每个按钮的状态都会发生我不想要的变化。有什么方法可以单独控制这些切换的状态

这是我要在表中使用的列的代码:

const COLUMNS = useMemo (() => [
      {
    Header: "Username",
    accessor: "Username",
    textAlign: "left",
    sortable: false,
    },
    {
    Header: "Status",
      accessor: "Status",
      textAlign: "center",
      Cell: ({ value, cell: { row } }) => (
        <div>
        <FormControlLabel
          control={
            <IOSSwitch
              checked={status}
              onClick={toggler}
              name="status"
            />
          }
          />
          
          {status ? <span>Active</span> : <span>Inactive</span>}
         
          </div>
      ),
    },

这是我的表格代码:

<Table {...getTableProps()}>
              <thead>
                {headerGroups.map((headerGroup) => (
                  <tr {...headerGroup.getHeaderGroupProps()}>
                    {headerGroup.headers.map((column) => (
                      <Th
                        {...column.getHeaderProps({
                          style: { textAlign: column.textAlign },
                        })}
                      >
                        {column.render("Header")}
                      </Th>
                    ))}
                  </tr>
                ))}
              </thead>
              <tbody {...getTableBodyProps()}>
                {page.map((row) => {
                  prepareRow(row);
                  return (
                    <Tr {...row.getRowProps()}>
                      {row.cells.map((cell) => {
                        return (
                          <Td
                            {...cell.getCellProps({
                              style: { textAlign: cell.column.textAlign },
                            })}
                          >
                            {cell.render("Cell")}
                          </Td>
                        );
                      })}
                    </Tr>
                  );
                })}
              </tbody>
            </Table>

标签: reactjs

解决方案


您必须将每个按钮分配给其单独的状态,例如,您可以为三个按钮设置三种状态。

您的状态应如下所示:

const [firstButton, setFirstButton] = useState(false)
const [secondButton, setSecondButton] = useState(false)
const [thirdButton, setThirdButton] = useState(false)

在你的 onClicks 中你应该说:

例如第二个按钮:

onClick={()=>setSecondButton(false)}

当您想在表格中使用此状态时,您应该将每个按钮与其状态相匹配

ps:如果您的按钮数量不固定,您应该编写一个函数来返回一个对象,其中键是按钮名称,值是 false(默认为 false,单击时应该更改)。

由于 react.js 中状态的不可变性,您应该克隆状态并更改您想要的内容,并保留其他所有内容,然后更新整个状态。

并像这样使用它:

onClick={()=>setButtonsState({...buttonsState, secondButton:false})}

buttonState 就像:

const [buttonsState, setButtonsState] = useState(
{
  firstButton: false,
  secondButton: false,
  thirdButton: false
}
)

推荐阅读