iT邦幫忙

2025 iThome 鐵人賽

DAY 25
0
生成式 AI

30天用React打造AI工具箱系列 第 25

30天用React打造AI工具箱 Day25

  • 分享至 

  • xImage
  •  

讓筆記活起來!新增編輯與更新功能

今日目標

在每則筆記上新增「編輯」按鈕。
點擊「編輯」後,將該筆記的標題、內容與標籤帶入上方的輸入框中。
在編輯模式下,將「新增筆記」按鈕切換為「更新筆記」與「取消」按鈕。
完成更新後,儲存變更並刷新筆記列表。

實作思路

要實現編輯功能,我們需要一個狀態(state)來追蹤「目前正在編輯哪一則筆記」。這能幫助我們切換 UI 模式並處理對應的邏輯。

  1. 新增編輯狀態
    首先,我們在組件中新增一個 state,例如 editingNoteId,用來儲存正在編輯的筆記 id。當它的值為 null 時,代表處於「新增模式」;反之,若有 id 值,則代表正在編輯某則特定筆記。

    import { useState, useEffect } from "react";
    
    export default function NoteManager() {
      // ... 其他 state
      const [editingNoteId, setEditingNoteId] = useState(null);
    
      // ...
    }
    
  2. 進入編輯模式
    當使用者點擊某則筆記的「編輯」按鈕時,我們會觸發一個函式(例如 startEditing)。這個函式會做兩件事:

    • 找到對應的筆記資料。
    • 將資料填入輸入框,並設定 editingNoteId。
    // 在 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);
    };
    
  3. 動態切換按鈕與邏輯
    接著,我們可以透過 editingNoteId 來判斷當前模式,並動態顯示不同的按鈕。

    • 如果 editingNoteId 是 null,顯示「新增筆記」按鈕。
    • 如果 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>
    
  4. 更新與取消
    最後,我們需要實作 updateNote 和 cancelEdit 兩個函式。

    • updateNote:使用 .map() 遍歷 notes 陣列,找到 id 相符的筆記,用新資料替換它,並重置表單。
    • cancelEdit:清空所有輸入框並將 editingNoteId 設回 null。
    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,我們將進一步優化使用者體驗,例如為「刪除」功能加上二次確認的提示框,避免使用者誤觸。


上一篇
30天用React打造AI工具箱 Day24
下一篇
30天用React打造AI工具箱Day26
系列文
30天用React打造AI工具箱27
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言