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

React入门开发者求助:如何将笔记的 onChange 实时更新改为点击Save按钮时更新

Solution: Update Note Only on Save Button Click

Hey there! Let's tweak your note app to only update the note content when you click the Save button instead of updating in real-time. Here's what you need to do:

Step-by-Step Changes

  • Add local state to the Main component to temporarily store the title and body as the user types
  • Update input/textarea bindings to use this local state instead of directly modifying the active note
  • Hook up the Save button to push the temporary values to the main notes state when clicked

Modified Main.js Code

import { useState, useEffect } from "react"; // Add useState and useEffect
import bin from "../images/bin.png";
import magnifier from "../images/magnifier.png";

const Main = ({ onDeleteNote, activeNote, onUpdateNote }) => {
  // Initialize local state with active note's data, or empty values if no active note
  const [localTitle, setLocalTitle] = useState(activeNote?.title || "");
  const [localBody, setLocalBody] = useState(activeNote?.body || "");

  // Update local state when activeNote changes (e.g., switching to a different note)
  useEffect(() => {
    if (activeNote) {
      setLocalTitle(activeNote.title);
      setLocalBody(activeNote.body);
    }
  }, [activeNote]);

  // Handler for Save button click
  const handleSaveNote = () => {
    if (activeNote) {
      onUpdateNote({
        ...activeNote,
        title: localTitle,
        body: localBody,
      });
    }
  };

  if (!activeNote) return (
    <div className="app-main">
      <div className="search">
        <input type="text" placeholder="Search by title" className="search-input" />
        <img src={magnifier} alt="search" style={{cursor: 'pointer'}} />
      </div>
      <div className="no-active-note">No Active Note</div>
    </div>
  );

  return (
    <div className="app-main">
      <div className="search">
        <input type="text" placeholder="Search by title" className="search-input" />
        <img src={magnifier} alt="search" style={{cursor: 'pointer'}} />
      </div>
      <div className="app-main-note-edit">
        <div className="main-title-block">
          <p>Title</p>
          <img
            src={bin}
            alt="Delete"
            height={50}
            width={41}
            onClick={() => onDeleteNote(activeNote.id)}
            style={{cursor: 'pointer'}}
          />
        </div>
        <input
          type="text"
          id="title"
          placeholder="Note title"
          value={localTitle} // Bind to local state
          onChange={(e) => setLocalTitle(e.target.value)} // Update local state on type
          autoFocus
        />
        <p>Description</p>
        <textarea
          id="body"
          placeholder="Write your note here..."
          value={localBody} // Bind to local state
          onChange={(e) => setLocalBody(e.target.value)} // Update local state on type
        />
        <div className="app-buttons">
          <button onClick={handleSaveNote} className="button-new-save"> {/* Add click handler */}
            Save
          </button>
        </div>
      </div>
    </div>
  );
};

export default Main;

Key Explanations

  1. Local State: We added localTitle and localBody to hold the user's input as they type—this keeps the main notes state untouched until the user decides to save.
  2. useEffect: This ensures that when you switch to a different note, the local state updates to match the new active note's content. Without this, typing in one note and switching would leave the old input in the fields.
  3. Save Handler: The handleSaveNote function sends the temporary local values to onUpdateNote, which then updates the main notes state just like it did before—but only when the button is clicked.
  4. Input Bindings: The input and textarea now use the local state for their values, so typing updates the local state instead of triggering an immediate save.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 11:22:46