1

我正在使用 DraftJS 编辑文本内容,但是当我尝试编辑从 DB 检索并加载到编辑器中的任何现有内容时,光标会自动跳转到文本的开头,并且我开始从反向输入。

我已经导入了Editorinto Bulletin.js,所以我必须通过in 的函数getContent传入Editor并检索原始 html来获取内容。getContenthandleEditorChangeEditor

我发现如果我删除了getContent将原始 HTML 传回的功能handleEditorChange,编辑器可以正常工作,但是我将无法将 html 内容返回到Bulletin.js.

是我创建的代码框以供参考。

4

1 回答 1

1

问题是您在此处为每个更改设置了一个新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]);

htmlContent当您通过函数将每次更改转换EditorState为 HTML 时,它总是在变化。getContent

如果你想用 初始化你EditorState的,htmlContent你可以在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()
});
于 2021-08-17T06:01:47.753 回答