如何在react draft wysiwyg中设置初始编辑器状态



在将react-draft-wysiwyg文本编辑器中的数据存储到服务器端时,我使用此函数将其转换为JSON。

content = JSON.stringify(
convertToRaw(state.editorState.getCurrentContent()),
);

当我检索数据时它在JSON中是这样的

"{"blocks":[{"key":"b4n4u","text":"Hi ","type":"unstyled","depth":0,"inlineStyleRanges":[],"entityRanges":[],"data":{}},{"key":"bp5jr","text":"fgfgfgfgfgfg","type":"header-two","depth":0,"inlineStyleRanges":[{"offset":0,"length":12,"style":"fontsize-8"}],"entityRanges":[],"data":{}},{"key":"81j28","text":"","type":"unstyled","depth":0,"inlineStyleRanges":[],"entityRanges":[],"data":{}},{"key":"1nljr","text":"dfdfdf","type":"unordered-list-item","depth":0,"inlineStyleRanges":[{"offset":0,"length":6,"style":"fontsize-8"}],"entityRanges":[],"data":{}},{"key":"b629m","text":"dfdfdf","type":"unordered-list-item","depth":0,"inlineStyleRanges":[{"offset":0,"length":6,"style":"fontsize-8"}],"entityRanges":[],"data":{}},{"key":"3afsd","text":"dfdfdf","type":"unordered-list-item","depth":0,"inlineStyleRanges":[{"offset":0,"length":6,"style":"fontsize-8"}],"entityRanges":[],"data":{}},{"key":"1rq6j","text":"dfdf","type":"unordered-list-item","depth":0,"inlineStyleRanges":[{"offset":0,"length":4,"style":"fontsize-8"}],"entityRanges":[],"data":{}},{"key":"536hu","text":"df","type":"unordered-list-item","depth":0,"inlineStyleRanges":[{"offset":0,"length":2,"style":"fontsize-8"}],"entityRanges":[],"data":{}}],"entityMap":{}}",

现在,我希望这是另一个页面的编辑器的initialState

所以我尝试使用defaultEditorState在文档https://jpuri.github.io/react-draft-wysiwyg/#/docs中提到的

<Editor
defaultEditorState={convertFromRaw(JSON.parse(post.content))}
editorState={state.editorState}
wrapperClassName='blogpost-text-editor-wrapper'
editorClassName='blogpost-text-editor'
toolbarClassName='blogpost-text-editor-toolbar'
onEditorStateChange={onChange}
/>

但是它不起作用。从draft.js文档的EditorState页面是缺失的,所以我不知道如何创建一个EditorState对象。请帮我一下。

任何帮助都将是非常感激的。

我找到了一个方法。假设。content有ContentState,我们可以这样初始化EditorState

const [state, setState] = useState({
editorState: EditorState.createWithContent(
convertFromRaw(JSON.parse(post.content)),
),
});
import htmlToDraft from 'html-to-draftjs';

const contentBlocks = htmlToDraft(initialState)
const contentState = ContentState.createFromBlockArray(contentBlocks)
const rawHtml = convertToRaw(contentState)


<Editor contentState={rawHtml} />

使用htmlToDraft保持HTML的样式/css;convertFromRaw会造成颜色损失。

最新更新