【问题标题】:React DraftJS cursor auto jumps to beginning after typing in existing content and started typing backwards?React DraftJS 光标在输入现有内容后自动跳转到开头并开始向后输入?
【发布时间】:2021-10-17 07:36:38
【问题描述】:

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

我已将Editor 导入Bulletin.js,因此我必须通过将getContent 传递给Editor 来获取内容,并在handleEditorChange 函数中使用getContent 检索原始html Editor

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

Here's 我创建的代码框供参考。

【问题讨论】:

    标签: javascript reactjs draftjs react-draft-wysiwyg


    【解决方案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 始终在发生变化,因为您通过 getContent 函数在每次更改时将 EditorState 转换为 HTML。

    如果您想用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()
    });
    

    【讨论】:

    • 我应该如何更改 getContent 的工作方式,以便它不会在每次更改时将 EditorState 转换为 HTML?不太确定我是否理解正确。
    • getContent 方法不是问题,useEffect 中的setEditorState 是问题。只需在创建组件时执行一次,而不是在每次更改时执行一次
    • 如果我得到这个正确,我只需要从 useEffect 中删除 [htmlContent] 依赖对吗?
    • 我已经编辑了我的答案,希望现在更清楚。
    • 我明白你现在的意思了,谢谢。我已经尝试了您的方法并在我提供的代码框中实现了它,但现在编辑器没有加载我传递给它的 html 内容(<p>Hello world</p>) 出于某种原因。
    猜你喜欢
    • 2019-06-10
    • 2021-08-19
    • 2020-10-25
    • 2016-06-27
    • 2017-10-07
    • 2011-01-08
    • 2022-08-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多