首頁  >  問答  >  主體

如何修復react中關於狀態的這個錯誤?

我想做一個簡單的反應應用程序,當我在一個塊上按回車鍵時,一個新塊將顯示在該塊下,而後面的其餘部分將在新塊下。

但是當有多個區塊時,當我在前一個區塊上按回車鍵時,後一個區塊就會消失。

我不明白。有人能指出這個錯誤嗎?

以下是一些程式碼和圖片:

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 鍵後:

我發現該錯誤來自區塊,但我不明白為什麼會發生這種情況。

P粉214176639P粉214176639226 天前397

全部回覆(1)我來回復

  • P粉557957970

    P粉5579579702024-04-02 08:08:07

    這是 react-contenteditable 的已知問題,請參考 lovasoa/react-contenteditable# 161:

    在連結問題中提出的解決方法中,您可以嘗試該評論,它是useEventCallback 的變體every-change-value-from-usecallback" rel="nofollow noreferrer">遺留React 文件> 如何從useCallback 讀取經常變化的值? :

    const useRefCallback = (
      value: ((...args: T) => void) | undefined,
      deps?: React.DependencyList
    ): ((...args: T) => void) => {
      const ref = React.useRef(value);
    
      React.useEffect(() => {
        ref.current = value;
      }, deps ?? [value]);
    
      const result = React.useCallback((...args: T) => {
        ref.current?.(...args);
      }, []);
    
      return result;
    };
    
    // Usage
    export function EditablePage() {
      // State, addBlockHandler function...
    
      const addBlock2 = useRefCallback(addBlockHandler);
    
      return (
        
    {blocks.map(({ tag, content, position }: BlockType) => { return ( ); })}
    ); }

    回覆
    0
  • 取消回覆