reactjs - 在反应表中单独切换多个按钮
问题描述
非活动状态:
活动状态:
当我切换一个按钮时,其他每个按钮的状态都会发生我不想要的变化。有什么方法可以单独控制这些切换的状态
这是我要在表中使用的列的代码:
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>
解决方案
您必须将每个按钮分配给其单独的状态,例如,您可以为三个按钮设置三种状态。
您的状态应如下所示:
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
}
)
推荐阅读
- sql - oracle物化视图日志中的复合分区
- html - 即使窗口小于图像的宽度,如何在 CSS 中修复图像的高度
- c++ - GLFW,使用 glClear 从屏幕左上角的奇数偏移
- python - 使用 Selenium 页面提交表单后,只需重新加载
- python-3.x - mplfinance 烛台堆积在图表上,没有前进
- python - 如何从颜色轮廓创建颜色图/热图?
- python - 如果这些字符串略有不同,如何根据另一个列表中的字符串从列表中删除某些字符串?更多信息如下
- tensorflow - 为什么 VGG-16 在 CIFAR-10 数据集上表现不佳?
- c++ - 无法在 QT ubuntu 上使用 odbc 连接到 sql server
- bash - Shell 日期转换并分配给变量