【问题标题】:Fetch data from the backend, then pass the data to editorState using draft-js从后端获取数据,然后使用 Draft-js 将数据传递给 editorState
【发布时间】:2022-01-01 01:45:33
【问题描述】:

我正在创建一个组件,该组件将使用 Draft-js 显示来自后端的数据。来自后端的数据也使用 Draft-js 存储。数据不显示,也没有错误信息。

来自后端的样本数据在传递给 viewContent.js 之前被解析

你好世界

我尝试创建一个变量来检查代码是否正常工作。我尝试了这种方法 const sample = <p>Hello World。如果在 contenBlocks 上传递这个,这个就可以工作了。

viewContent.js

import {
  EditorState,
  ContentState,
  convertFromHTML,
} from 'draft-js';
import { Editor } from 'react-draft-wysiwyg';
import draftToHtml from 'draftjs-to-html';

const viewContent = ({ content }) => {
    const [editorState, setEditorState] = useState();

  const clearState = () => {
    ContentState.createFromText('');
  };

  const handleEditorChange = (state) => {
    setEditorState(state);
    let currentContentAsHTML = JSON.stringify(
      draftToHtml(convertToRaw(editorState.getCurrentContent()))
    );
    convertedContent(currentContentAsHTML);
  };

  useEffect(() => {
    const contentBlocks = convertFromHTML(content);

    const contentState = ContentState.createFromBlockArray(
      contentBlocks.contentBlocks,
      contentBlocks.entityMap
    );

    setEditorState(EditorState.createWithContent(contentState));
  }, [content]);

  return (
    <div className='comment-container p-2 border rounded-md'>
      <Editor
        editorState={editorState}
        onEditorStateChange={handleEditorChange}
        wrapperClassName='wrapper-class'
        editorClassName='editor-class'
        toolbarClassName='toolbar-class'
        onClick={clearState}
      />
    </div>
  );


};

export default viewContent;

父组件

<viewContent
                      content={taskInfo.taskNote}
                      convertedContent={(convertedContent) =>
                        setTaskInfo((prevState) => ({
                          ...prevState,
                          taskNote: convertedContent,
                        }))
                      }
                    />

错误

【问题讨论】:

    标签: reactjs draftjs react-draft-wysiwyg


    【解决方案1】:

    您应该在ViewContent 组件完全渲染后设置编辑器状态。如下更新您的组件:

    
    ...
    
    useEffect(() => {
      const contentBlocks = convertFromHTML(content);
    
      const contentState = ContentState.createFromBlockArray(
        contentBlocks.contentBlocks,
        contentBlocks.entityMap
      );
    
      setEditorState(EditorState.createWithContent(contentState));
    }, [content]);
    
    ...
    
    

    【讨论】:

    • 谢谢先生,当我点击编辑它在编辑器中添加一个新的行标签时,您是否遇到这种行为
    • 欢迎您,不,我以前没有遇到过这个问题。也许分享您的实现有助于解决它!
    • 我认为问题出在我试图将 onChange 值传递给父组件时。同时更新上面的代码
    • 如果在codeandbox之类的环境中重现此问题,我可以解决它,因为在代码中我找不到任何问题
    猜你喜欢
    • 1970-01-01
    • 2017-06-22
    • 1970-01-01
    • 2021-03-19
    • 1970-01-01
    • 1970-01-01
    • 2015-12-25
    • 1970-01-01
    相关资源
    最近更新 更多