React列表中实现编辑按钮仅作用于单个列表项的技术问询
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:
Update the state to store the ID of the editing item
Replace your boolean state with one that holds eithernull(no item being edited) or the ID of the item currently in edit mode:const [editingId, setEditingId] = useState(null);Modify the toggle function to target individual items
UpdateeditingTrainingto 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); };Adjust button rendering to check the current item’s ID
In yourmaploop, compare the current item’strainingsidtoeditingIdto 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:
editingIdnow tracks exactly which item is in edit mode (ornullif 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

