我想做一個簡單的反應應用程序,當我在一個塊上按回車鍵時,一個新塊將顯示在該塊下,而後面的其餘部分將在新塊下。
但是當有多個區塊時,當我在前一個區塊上按回車鍵時,後一個區塊就會消失。
我不明白。有人能指出這個錯誤嗎?
以下是一些程式碼和圖片:
editablePage.tsx
import { useState } from "react"; import EditableBlock, { BlockType } from "../editableBlock"; export default function EditablePage() { const [blocks, setBlocks] = useState<BlockType[]>([ { tag: "h1", content: "Welcome", position: 0 }, ]); function addBlockHandler({ tag, position }: BlockType) { const nextPosition = position + 1; const newBlock: BlockType = { tag: tag, content: nextPosition.toString(), position: nextPosition, }; console.log(blocks); const blocksBeforeNew = blocks.slice(0, nextPosition); const blocksAfterNew = blocks.slice(nextPosition).map((block) => { const copy = { ...block }; copy.position += 1; return copy; }); const updatedBlocks = blocksBeforeNew .concat(newBlock) .concat(blocksAfterNew); setBlocks(updatedBlocks); } return ( <div> {blocks.map(({ tag, content, position }: BlockType) => { return ( <EditableBlock key={position} tag={tag} position={position} content={content} addBlock={addBlockHandler} /> ); })} </div> ); }
editableBlock.tsx
import { useState } from "react"; import ContentEditable, { ContentEditableEvent } from "react-contenteditable"; type TagType = "h1" | "h2" | "h3" | "p"; export interface BlockType { tag: TagType; content: string; position: number; } export interface EditableBlockProps extends BlockType { addBlock: (currentBlock: BlockType) => void; } export default function EditableBlock({ tag, content, position, addBlock, }: EditableBlockProps) { const [text, setText] = useState<string>(content); const handleChange = (evt: ContentEditableEvent) => { setText(evt.target.value); }; const handleKeyDown = (evt: React.KeyboardEvent<HTMLElement>) => { if (evt.key === "Enter") { evt.preventDefault(); addBlock({ tag, content, position }); } }; return ( <ContentEditable tagName={tag} html={text} onChange={handleChange} onKeyDown={handleKeyDown} /> ); }
之前:
在第一個區塊上按 Enter 鍵後:
我發現該錯誤來自區塊,但我不明白為什麼會發生這種情況。
這是
react-contenteditable
的已知問題,請參考 lovasoa/react-contenteditable# 161:在連結問題中提出的解決方法中,您可以嘗試該評論,它是useEventCallback 的變體every-change-value-from-usecallback" rel="nofollow noreferrer">遺留React 文件> 如何從
useCallback
讀取經常變化的值? :