You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中实现勾选复选框仅显示当前行Delete按钮的问题

问题根源

你用了单一布尔值状态myCheck控制所有行的Delete按钮显示,只要任意复选框被勾选,这个状态就会变为true,导致所有行的按钮同时显示。要实现仅显示勾选行的按钮,必须为每一行单独维护勾选状态。

修复方案

把单一的myCheck改成存储勾选索引的数组,精准控制每一行的按钮显示:

import { useState } from 'react';

function App() {
  const games = ['cricket', 'volleyball', 'football'];
  const [gameList, setGameList] = useState(games);
  // 用数组存储被勾选的行索引,初始为空
  const [checkedIndices, setCheckedIndices] = useState([]);

  const deleteItem = (itemIndex) => {
    const updatedGames = gameList.filter((_, i) => i !== itemIndex);
    setGameList(updatedGames);
    // 删除行后同步移除对应的勾选状态
    setCheckedIndices(prev => prev.filter(index => index !== itemIndex));
  };

  const handleCheckboxChange = (index) => {
    setCheckedIndices(prev => {
      // 判断当前索引是否已在勾选列表中
      if (prev.includes(index)) {
        // 已勾选则移除
        return prev.filter(i => i !== index);
      } else {
        // 未勾选则添加
        return [...prev, index];
      }
    });
  };

  return (
    <div className="App">
      <h3>Play Games</h3>
      {gameList.map((ele, i) => (
        <div key={i}>
          <li>
            <input
              type="checkbox"
              // 根据当前索引是否在勾选数组中设置选中状态
              checked={checkedIndices.includes(i)}
              onChange={() => handleCheckboxChange(i)}
            />
            {ele}
            {/* 仅当当前行被勾选时显示Delete按钮 */}
            {checkedIndices.includes(i) && (
              <button onClick={() => deleteItem(i)}>Delete</button>
            )}
          </li>
        </div>
      ))}
    </div>
  );
}

export default App;
关键修改说明
  • 用checkedIndices数组替代单一myCheck,专门记录被勾选的行索引
  • 复选框的checked属性绑定当前索引是否在checkedIndices中,确保状态同步
  • handleCheckboxChange函数负责添加/移除对应索引,实现单一行的勾选状态切换
  • 渲染按钮时,仅在当前索引存在于checkedIndices时才显示

内容的提问来源于stack exchange,提问作者user21951352

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 09:42:48