0

所以我将 DraftJS 包与 React 以及提及插件一起使用。创建帖子后,我将原始 JS 存储在我的 PostreSQL JSONField 中:

convertToRaw(postEditorState.getCurrentContent())

当我编辑帖子时,我将编辑器状态设置如下:

let newEditorState = EditorState.createWithContent(convertFromRaw(post.richtext_content));
setEditorState(newEditorState);

文本设置正确,但没有突出显示任何提及,我无法添加新提及。有谁知道如何解决这一问题?

我正在使用提及插件:https ://www.draft-js-plugins.com/plugin/mention

4

1 回答 1

0

保存数据

 function saveContent() {
    const content = editorState.getCurrentContent();
    const rawObject = convertToRaw(content);
    const draftRaw = JSON.stringify(rawObject); //<- save this to database
 
}

和检索:

   setEditorState(()=> EditorState.push(
          editorState,
          convertFromRaw(JSON.parse(draftRaw)),
          "remove-range"
        ););

它应该将您的数据保存为已保存。

提供的示例(可以正常工作)用于插入带有提及的新块,同时保存 entityMap。提及数据只是一个简单的对象 {id:.., name:.., link:... , avatar:...}

还有一件事:只初始化一次:换句话说,不要重新创建状态。

const [editorState, setEditorState] = useState(() => EditorState.createEmpty() );

然后填充类似的内容:

 useEffect(() => {
   
    try {

      if (theDraftRaw) {
        let mtyState = EditorState.push(
          editorState,
          convertFromRaw(JSON.parse(theDraftRaw)),
          "remove-range"
        );
         setEditorState(mtyState);
      } else editorClear();

    } catch (e) {
      
      console.log(e);
      // or some fallback to other field  like text 
    
    }
  }, [theDraftRaw]);
  const editorClear = () => {

    if (!editorState.getCurrentContent().hasText()) return;

    let _editorState = EditorState.push(
      editorState,
      ContentState.createFromText("")
    );
    setEditorState(_editorState);
  };
于 2020-07-23T13:45:19.567 回答