React DraftJS 光标在输入现有内容并开始向后输入后自动跳转到开头?

React DraftJS cursor auto jumps to beginning after typing in existing content and started typing backwards?

我正在使用 DraftJS 编辑文本内容,但是当我尝试编辑我从数据库中检索并加载到编辑器中的任何现有内容时,光标自动跳转到文本的开头,我开始从后面打字。

我已经将 Editor 导入 Bulletin.js,所以我必须通过将 getContent 传递到 Editor 来获取内容并取回原始 html 通过在 Editor.

handleEditorChange 函数中使用 getContent

我发现如果我删除了 getContent 函数以在 handleEditorChange 中传回原始 HTML,编辑器可以正常工作,但我不会'无法将 html 内容恢复为 Bulletin.js

Here's我创建的codesandbox供参考。

问题是您在此处设置了每次更改的新 EditorState

useEffect(() => {
  if (htmlContent) {
    let convertedToHTML = decodeURIComponent(htmlContent);
    const blocksFromHtml = htmlToDraft(convertedToHTML);
    const { contentBlocks, entityMap } = blocksFromHtml;
    const contentState = ContentState.createFromBlockArray(
      contentBlocks,
      entityMap
    );
    setEditorState(EditorState.createWithContent(contentState));
  }
}, [htmlContent]);
当您通过 getContent 函数将 EditorState 转换为 HTML 时,

htmlContent 始终在变化。

如果你想用 htmlContent 初始化你的 EditorState 你可以在 useState 函数中完成它并删除 useEffect:

const [editorState, setEditorState] = useState(() => {
  if (htmlContent) {
    let convertedToHTML = decodeURIComponent(htmlContent);
    const blocksFromHtml = htmlToDraft(convertedToHTML);
    const { contentBlocks, entityMap } = blocksFromHtml;
    const contentState = ContentState.createFromBlockArray(
      contentBlocks,
      entityMap
    );
    return EditorState.createWithContent(contentState);
  }
  return EditorState.createEmpty()
});