在将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。
因此,我尝试使用文档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对象。请帮我弄一下这个。
任何帮助都将受到高度的感谢。
发布于 2021-08-02 08:26:21
我找到了这样做的方法。假设post.content有ContentState,我们可以这样初始化EditorState。
const [state, setState] = useState({
editorState: EditorState.createWithContent(
convertFromRaw(JSON.parse(post.content)),
),
});发布于 2021-09-13 08:13:48
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可能会导致颜色丢失。
https://stackoverflow.com/questions/68519755
复制相似问题