在ReactJS中如何获取表格行的rowIndex?
在React中获取表格行的rowIndex
你可以通过两种常用方法在React中获取表格行的rowIndex:
方法一:利用map的索引参数
在user.map遍历的时候,React会提供第二个参数索引值,结合表格thead的行数(通常是1行),就能计算出和原生rowIndex一致的数值:
const [user, setUser] = useState(null); const [rowIndex, setRowIndex] = useState(""); useEffect(() => { axios .get("http://localhost:8080/api/users") .then((response) => { setUser(response.data); }); }, []); // 原代码中依赖项`url`未定义,这里修正为空数组(或根据实际场景补充定义) const handleRowClick = (index) => { // 因thead有1行,实际rowIndex为索引+1 const actualRowIndex = index + 1; setRowIndex(actualRowIndex); console.log(actualRowIndex); }; const handleButtonClick = (index, e) => { // 阻止事件冒泡,避免触发tr的点击事件 e.stopPropagation(); const actualRowIndex = index + 1; console.log("按钮点击的行号:", actualRowIndex); }; if (user) { return ( <div> <table className="table"> <thead> <tr> <th scope="col">Name</th> <th scope="col">Age</th> <th scope="col">Department</th> <th scope="col">Action</th> </tr> </thead> <tbody> {user.map((item, index) => ( <tr key={item.id} onClick={() => handleRowClick(index)}> <td>{item.name}</td> <td>{item.age}</td> <td>{item.department}</td> <td> <button onClick={(e) => handleButtonClick(index, e)}>Click</button> </td> </tr> ))} </tbody> </table> </div> ); }
方法二:直接通过DOM元素获取rowIndex
和原生JS逻辑类似,在React的事件处理函数中,通过event.currentTarget拿到当前点击的<tr>元素,直接读取它的rowIndex属性:
const handleRowClick = (e) => { const currentRowIndex = e.currentTarget.rowIndex; setRowIndex(currentRowIndex); console.log(currentRowIndex); }; // 表格tbody部分的tr绑定事件 <tbody> {user.map((item) => ( <tr key={item.id} onClick={handleRowClick}> <td>{item.name}</td> <td>{item.age}</td> <td>{item.department}</td> <td> <button onClick={(e) => e.stopPropagation()}>Click</button> </td> </tr> ))} </tbody>
注意:这种方法的rowIndex会包含thead中的行(比如thead的<tr>rowIndex为0,tbody第一行rowIndex为1),和原生JS行为完全一致。另外,遍历列表时记得给每个<tr>添加唯一的key属性,这是React的最佳实践。
内容的提问来源于stack exchange,提问作者Jacky
相关产品推荐
相关产品推荐

