在每則筆記上新增「編輯」按鈕。
點擊「編輯」後,將該筆記的標題、內容與標籤帶入上方的輸入框中。
在編輯模式下,將「新增筆記」按鈕切換為「更新筆記」與「取消」按鈕。
完成更新後,儲存變更並刷新筆記列表。
要實現編輯功能,我們需要一個狀態(state)來追蹤「目前正在編輯哪一則筆記」。這能幫助我們切換 UI 模式並處理對應的邏輯。
新增編輯狀態
首先,我們在組件中新增一個 state,例如 editingNoteId,用來儲存正在編輯的筆記 id。當它的值為 null 時,代表處於「新增模式」;反之,若有 id 值,則代表正在編輯某則特定筆記。
import { useState, useEffect } from "react";
export default function NoteManager() {
// ... 其他 state
const [editingNoteId, setEditingNoteId] = useState(null);
// ...
}
進入編輯模式
當使用者點擊某則筆記的「編輯」按鈕時,我們會觸發一個函式(例如 startEditing)。這個函式會做兩件事:
// 在 map 筆記列表的地方,為每則筆記加上「編輯」按鈕
<div key={note.id}>
{/* ... 其他筆記內容 ... */}
<button onClick={() => startEditing(note)}>編輯</button>
<button onClick={() => deleteNote(note.id)}>刪除</button>
</div>
// 處理編輯的函式
const startEditing = (note) => {
setEditingNoteId(note.id);
setTitle(note.title);
setContent(note.content);
setTag(note.tag);
};
動態切換按鈕與邏輯
接著,我們可以透過 editingNoteId 來判斷當前模式,並動態顯示不同的按鈕。
// 在輸入區塊的按鈕位置
<div className="bg-white p-4 rounded shadow space-y-3">
{/* ... 輸入框 ... */}
{editingNoteId ? (
<>
<button onClick={updateNote} className="bg-green-600 ...">更新筆記</button>
<button onClick={cancelEdit} className="bg-gray-500 ...">取消</button>
</>
) : (
<button onClick={addNote} className="bg-blue-600 ...">新增筆記</button>
)}
</div>
更新與取消
最後,我們需要實作 updateNote 和 cancelEdit 兩個函式。
const updateNote = () => {
const updatedNotes = notes.map((note) =>
note.id === editingNoteId
? { ...note, title, content, tag, updatedAt: new Date().toLocaleString() }
: note
);
setNotes(updatedNotes);
cancelEdit(); // 重置狀態
};
const cancelEdit = () => {
setEditingNoteId(null);
setTitle("");
setContent("");
setTag("");
};
今天,我們成功地為筆記管理工具賦予了「生命」,讓它不再只是一個只能新增和刪除的列表,而是一個可以持續修改、更新的動態工具。透過引入一個 editingNoteId 狀態,我們巧妙地複用了原有的輸入表單,並實現了模式之間的切換,完成了 CRUD 的最後一塊拼圖。
至此,我們的筆記工具已具備了所有核心功能。明天 Day 26,我們將進一步優化使用者體驗,例如為「刪除」功能加上二次確認的提示框,避免使用者誤觸。