问题描述
在将数据从 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\",\"inlinestyleRanges\":[{\"offset\":0,\"length\":12,\"style\":\"fontsize-8\"}],{\"key\":\"81j28\",\"text\":\"\",{\"key\":\"1nljr\",\"text\":\"dfdfdf\",\"type\":\"unordered-list-item\",\"length\":6,{\"key\":\"b629m\",{\"key\":\"3afsd\",{\"key\":\"1rq6j\",\"text\":\"dfdf\",\"length\":4,{\"key\":\"536hu\",\"text\":\"df\",\"length\":2,\"data\":{}}],\"entityMap\":{}}",
所以我尝试使用文档 https://jpuri.github.io/react-draft-wysiwyg/#/docs
中提到的 defaultEditorState<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 对象。请帮我解决这个问题。
任何帮助将不胜感激。
解决方法
我找到了一种方法来做到这一点。假设 post.content 有 ContentState,我们可以像这样初始化 EditorState。
const [state,setState] = useState({
editorState: EditorState.createWithContent(
convertFromRaw(JSON.parse(post.content)),),});