next.js 如何在contentEditable div中的p标签中添加新行

3duebb1j  于 2023-11-18  发布在  其他
关注(0)|答案(2)|浏览(129)

我有一个contentEditable div,每当我通过按enter或shift+enter插入一个新行时,新行是div中的textNode,但我希望新行位于p元素中。
我想要一个简单的解决方案
我使用React Js,所以我保存contentEditable div的内容,状态名为content,由onChange更新,我使用react-contenteditable组件包

jc3wubiy

jc3wubiy1#

您可以处理onKeyDown事件来拦截Enter键并手动插入<p>元素。

import React, { useState } from 'react';
import ContentEditable from 'react-contenteditable';

const App = () => {
  const [content, setContent] = useState('<p>Start typing...</p>');

  const handleKeyDown = (e) => {
    if (e.key === 'Enter') {
      e.preventDefault(); // Prevent the default behavior (new line)
      setContent((prevContent) => `${prevContent}<p><br></p>`); // Insert a <p> element
    }
  };

  return (
    <ContentEditable
      html={content}
      onChange={(e) => setContent(e.target.value)}
      onKeyDown={handleKeyDown}
    />
  );
};

export default App;

字符串

vkc1a9a2

vkc1a9a22#

const insertNewLine = (e) => {
        if (e.key === 'Enter') {
            e.preventDefault();

            // Create a new <p> element
            const newParagraph = document.createElement('p');
            newParagraph.innerHTML = '<br>'; // Add a line break to make the new paragraph visible

            // Insert the new <p> element after the current selection
            const selection = window.getSelection();
            const range = selection.getRangeAt(0);
            range.deleteContents();
            range.insertNode(newParagraph);

            // Move the caret inside the new <p> element
            const newRange = document.createRange();
            newRange.setStart(newParagraph, 0);
            newRange.setEnd(newParagraph, 0);
            selection.removeAllRanges();
            selection.addRange(newRange);
        }
    };

字符串

相关问题