React JS中如何在选中0或多个表格复选框时禁用按钮
问题根因
- 原有逻辑依赖DOM层级计算复选框的全局索引,表格场景下每个复选框被独立的
<td>包裹,e.target.parentNode.children中只有当前1个复选框,计算得到的索引永远为0,无法正确对应全局状态数组的位置。
修复方案
- 放弃通过DOM结构计算索引,直接给每个复选框显式绑定索引,不依赖布局结构,稳定性更高。修改后代码如下:
import React, { useState } from "react"; import "./styles.css"; function Example() { // 初始化状态和复选框数量一致,3个复选框就初始化为3个false const [boxes, setBoxes] = useState([false, false, false]); // 新增index参数接收显式传入的索引 function handleChange(e, index) { const newState = [...boxes]; newState[index] = !newState[index]; setBoxes(newState); } function isDisabled() { const len = boxes.filter((box) => box).length; return len === 0 || len > 1; } return ( <div className="App"> <button disabled={isDisabled()}>Click Me</button> <table> <thead> <th>One</th> <th>Two</th> <th>Three</th> </thead> <tbody> <tr> <td> {/* 给第一个复选框传入索引0 */} <input type="checkbox" onChange={(e) => handleChange(e, 0)} /> </td> <td> two data</td> <td> three data</td> </tr> <tr> <td> {/* 给第二个复选框传入索引1 */} <input type="checkbox" onChange={(e) => handleChange(e, 1)} /> </td> <td> two data</td> <td> three data</td> </tr> <tr> <td> {/* 给第三个复选框传入索引2 */} <input type="checkbox" onChange={(e) => handleChange(e, 2)} /> </td> <td> two data</td> <td> three data</td> </tr> </tbody> </table> </div> ); } export default Example;
如果你的表格行是动态生成的,直接在遍历行数据时把map方法的第二个参数(索引)传入handleChange即可,不用硬编码索引值。
内容的提问来源于stack exchange,提问作者creativated
相关产品推荐
相关产品推荐

