问题描述
我正在使用带有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
,您将删除插件添加的所有装饰器。