我试图将draft-js
的EditorContent
保存到数据库中,然后再读取和重新创建EditorContent对象,但是EditorContent.getPlainText()
删除了丰富的文本内容,我不知道其他方法。
如何正确持久化EditorContent
发布于 2016-04-08 04:55:55
顾名思义,getPlainText()
方法只返回纯文本,没有任何丰富的格式设置。您应该使用convertToRaw()和convertFromRaw()函数来序列化和反序列化编辑器的内容。
如果有必要,可以以这种方式导入它们:(假设您使用的是ES6)
import {convertFromRaw, convertToRaw} from 'draft-js';
如果需要导出HTML,请参阅https://medium.com/@rajaraodv/how-draft-js-represents-rich-text-data-eeabb5f25cf2#9260 (但不确定是否可以从HTML导入内容)
发布于 2017-03-13 20:11:14
我发现在读取数据库并将其保存到数据库时,必须使用stringify
和parse
来实现RawContentState对象。
import { convertFromRaw, convertToRaw } from 'draft-js';
// the raw state, stringified
const rawDraftContentState = JSON.stringify( convertToRaw(this.state.editorState.getCurrentContent()) );
// convert the raw state back to a useable ContentState object
const contentState = convertFromRaw( JSON.parse( rawDraftContentState) );
发布于 2017-10-25 04:32:23
这里有很多有用的答案,所以我想添加这个小提琴演示。它展示了它是如何运作的。为了保存和检索编辑器的内容,这里使用了local storage
。但是对于数据库来说,基本原理是一样的。
在这个演示中,您可以看到简单的编辑器组件,当您单击SAVE RAW CONTENT TO LOCAL STORAGE
时,我们将当前编辑器内容作为字符串保存到本地存储中。我们使用convertToRaw
和JSON.stringify
来实现它:
saveRaw = () => {
var contentRaw = convertToRaw(this.state.editorState.getCurrentContent());
localStorage.setItem('draftRaw', JSON.stringify(contentRaw));
}
如果在此之后重新加载页面,则将使用保存的内容和样式初始化编辑器。在constructor
中,我们读取适当的本地存储属性,并使用JSON.parse
、convertFromRaw
和createWithContent
方法使用先前存储的内容初始化编辑器。
constructor(props) {
super(props);
let initialEditorState = null;
const storeRaw = localStorage.getItem('draftRaw');
if (storeRaw) {
const rawContentFromStore = convertFromRaw(JSON.parse(storeRaw));
initialEditorState = EditorState.createWithContent(rawContentFromStore);
} else {
initialEditorState = EditorState.createEmpty();
}
this.state = {
editorState: initialEditorState
};
}
https://stackoverflow.com/questions/36499858
复制相似问题