簡體   English   中英

在模態中編輯 state

[英]Editing state inside a modal

我正在做一個小筆記應用程序。 當用戶寫下他們的標題和注釋並單擊提交時,注釋會被放置在頁面上......我希望能夠編輯注釋。 單擊編輯按鈕時,會彈出一個模式,我希望用戶標題和注釋位於模式的輸入框中。

這是一張圖片,可以更好地理解。 [1]: https://i.stack.imgur.com/9cFSh.png

我希望標題和注釋位於輸入框中,允許用戶編輯它們。 下面是我的模態組件,我在下面寫的 function 運行良好,但它不是“編輯”原始標題或注釋,它基本上只是制作一個新標題或注釋。

知道如何在模態輸入框中獲取標題和注釋並根據需要直接修改它們嗎? 提前致謝!

import React, { useState } from "react";

export default function Modal({
  title,
  note,
  setCompletedNote,
  FullNote,
  setIsModalShown,
  ...props
}) {
  const [newTitle, setNewTitle] = useState("");
  const [newNote, setNewNote] = useState("");

  function editNoteCompleted(id, newTitle, newNote, e) {
    setCompletedNote((prevState) =>
      prevState.map((n) => {
        if (n.id === id) {
          return { ...n, title: newTitle, note: newNote }; 
        }
        return n; 
      })
    );

    setIsModalShown(false);
  }

  return (
    <div className="modal__container">
      <div className="modal__note-information">
        <p>Edit Note:</p>
        <input
          type="text"
          name="newTitle"
          value={newTitle}
          onChange={(e) => setNewTitle(e.target.value)}
        />
        <br />
        <input
          type="text"
          value={newNote}
          name="newNote"
          onChange={(e) => setNewNote(e.target.value)}
        />

        <div className="modal__button-container">
          <button
            className="modal__ok-button"
            onClick={() => editNoteCompleted(FullNote.id, newTitle, newNote)}
          >
            Ok
          </button>
          <button className="modal__cancel-button">Cancel</button>
        </div>
      </div>
    </div>
  );
}

如果所選組件的標題和注釋作為道具傳遞。 然后,您只需要將 state 的 initialValue 作為titlenote道具。

export default function Modal({
  title, 
  note,
  setCompletedNote,
  FullNote,
  setIsModalShown,
  ...props
}) {
  const [newTitle, setNewTitle] = useState(title || ''); 
  const [newNote, setNewNote] = useState(note || '');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM