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

React列表中实现编辑按钮仅作用于单个列表项的技术问询

Fix: Toggle Edit/Save Buttons for Individual List Items

The core issue here is that you’re using a single boolean state (editing) to control every item in your list—so when you toggle it, all items react to the same state change. To fix this, you need to track which specific item is being edited instead of a global true/false value.

Here’s how to adjust your code step by step:

  1. Update the state to store the ID of the editing item
    Replace your boolean state with one that holds either null (no item being edited) or the ID of the item currently in edit mode:

    const [editingId, setEditingId] = useState(null);
    
  2. Modify the toggle function to target individual items
    Update editingTraining to either set the editing ID to the clicked item’s ID (if it’s not already being edited) or clear it (to switch back to Edit mode):

    const editingTraining = (id) => {
      console.log("Editing works");
      // Toggle: if we're already editing this item, stop; else start editing it
      setEditingId(prevId => prevId === id ? null : id);
    };
    
  3. Adjust button rendering to check the current item’s ID
    In your map loop, compare the current item’s trainingsid to editingId to decide which button to show:

    {trainingData.map((d, i) => (
      <div key={i}>
        {/* Show Edit button if this item is NOT being edited */}
        {editingId !== d.trainingsid && (
          <button className="button is-info" onClick={() => editingTraining(d.trainingsid)}>
            Edit
          </button>
        )}
        {/* Show Save button if this item IS being edited */}
        {editingId === d.trainingsid && (
          <button className="button is-success" onClick={() => editingTraining(d.trainingsid)}>
            Save
          </button>
        )}
        <br />
      </div>
    ))}
    

Why this works:

  • editingId now tracks exactly which item is in edit mode (or null if none are).
  • Each list item checks its own ID against editingId, so only the clicked item’s buttons will toggle state.
  • Clicking the Save button for an item will switch it back to Edit mode, and clicking a different Edit button will stop editing the current item and start editing the new one.

If you ever want to allow editing multiple items at once, you could use a Set to store all active editing IDs—but this single-item approach aligns perfectly with your original requirement.

内容的提问来源于stack exchange,提问作者Mr. Hankey

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 07:57:41