我的博客写作输入正在删除 react 中的最后一行

问题描述 投票:0回答:0

这是我在当前输入中有 4 行和第 5 行的当前状态

这是我的反应代码


import { FC, useEffect, useState } from "react";

interface BlogWitterProps {}

const BlogWitter: FC<BlogWitterProps> = ({}) => {
  const [markdownContent, setMarkdownContent] = useState("");
  const [currentLine, setCurrentLine] = useState("");

  // on each new line, update the markdown content

  useEffect(() => {
    console.log("markdownContent", markdownContent);
    console.log("currentLine", currentLine);
  }, [currentLine, markdownContent]);

  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === "Enter") {
      setMarkdownContent((prev) => {
        return prev + currentLine + "\n";
      });
      setCurrentLine("");
    } else if (e.key === "Backspace" && currentLine === "") {
      e.preventDefault();
      setMarkdownContent((prev) => {
        const lines = prev.split("\n");
        const lastLine = lines.pop();
        console.log("lines", lines);

        setTimeout(() => {
          // If the last line is not empty, update the current line state
          if (lastLine !== "") {
            setCurrentLine(lastLine + "\n");
          } else {
            setCurrentLine("");
          }
        }, 0);

        return lines.join("\n");
      });
    }
  };

  return (
    <div className="">
      <div>
        {markdownContent.split("\n").map((line, index) => {
          return (
            <div key={index}>
              {line}
              <br />
            </div>
          );
        })}
      </div>
      <input
        value={currentLine}
        onChange={(e) => {
          setCurrentLine(e.target.value);
        }}
        className="w-full resize-none outline-none text-2xl bg-transparent border border-black"
        onKeyDown={handleKeyDown}
      />
    </div>
  );
};

export default BlogWitter;

因此,如果我按退格键,它会带我到最后一行进行编辑,然后在不更改任何内容的情况下再次按前键,它会删除最后一行的新行并给我这个

我正在尝试让它像在 medieum 中一样工作,您可以在其中单独编辑每一行

javascript css reactjs react-hooks next
© www.soinside.com 2019 - 2024. All rights reserved.