Draft.js 向编辑器呈现 contentState 后提及插件不工作

Draft.js Mention Plugin is not working after rendering contentState to the editor

我在 draft.js 中使用提及项(例如 @yourname)并发送到数据库以保存并获取它以在网页上呈现,但事情没有按预期工作。

正在保存到数据库中 ->

const contentState = editorState.getCurrentContent();
const currentStateData = convertToRaw(contentState);
const richStringifyValue = JSON.stringify(currentStateData);
// sending richStringifyValue to save in Mongo DB

在编辑器中获取和设置 ->

const [editorState, setEditorState] = React.useState(() => EditorState.createEmpty());
const parsedData = JSON.parse(post.contentStyled);
const fromRawData = convertFromRaw(parsedData );
EditorState.createWithContent(fromRawData);


// here is the view rendered part -
   <Editor 
     readOnly={true}
     editorState={editorState}
   />

但在编辑器中设置后(从 API 获取数据后)我的提及 (@... @... @...) 丢失了 CSS。我们该怎么办?

关于使用编辑 ->

在编辑器中再次获取和设置 ->

我不知道为什么会这样,请帮助解决这个问题!

您应该执行以下操作:

const [editorState, setEditorState] = React.useState(() => {
  const parsedData = JSON.parse(post.contentStyled);
  const fromRawData = convertFromRaw(parsedData );
  return EditorState.createWithContent(fromRawData);
});

// ...
   <Editor 
     readOnly={true}
     editorState={editorState}
   />

如果您用新创建的状态覆盖 editorState,您将删除插件添加的所有装饰器。

Dominic 的回答让我意识到装饰器的问题,但他的方法对我也不起作用。

我最终做的是避免完全安装编辑器,直到我将数据放入 EditorState 中:

const [editorState, setEditorState] = React.useState(null);

useEffect(() => {
  const parsedData = JSON.parse(post.contentStyled);
  const fromRawData = convertFromRaw(parsedData );
  setEditorState(() => EditorState.createWithContent(fromRawData));
}, []);

editorState && <Editor readOnly={true} editorState={editorState}/>

通过这种方式,您可以在实例化组件之前将持久数据插入到状态中。之后任何其他添加装饰器的插件都将按预期工作。