Draft js. Persist EditorContent to database

感情迁移 提交于 2019-12-02 22:04:39

The getPlainText() method, as its name suggests, only returns the plain text without any rich formatting. You should use the convertToRaw() and convertFromRaw() functions to serialize and deserialize the contents of the editor.

You can import them this way if necessary: (assuming you are using ES6)

import {convertFromRaw, convertToRaw} from 'draft-js';

If you need to export HTML instead, see https://medium.com/@rajaraodv/how-draft-js-represents-rich-text-data-eeabb5f25cf2#9260 (not sure you can import the contents back from HTML, though)

I've found that I must stringify and parse the RawContentState object when reading and saving to the database.

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) );

To persist

const contentStateJsObject = ContentState.toJS();
const contentStateJsonString = JSON.stringify(contentStateJS);

now content state can be persisted as JSON string.

To recreate ContentState

const jsObject = JSON.parse(jsonString);
const contentState = new ContentState(jsObject);

There are a bunch of useful answers here so I want to add this jsfiddle demo. It shows how it works in action. For saving and retrieving of the content of the editor, here local storage is used. But for database case, the basic principle the same.

In this demo, you can see simple editor component, when you click on SAVE RAW CONTENT TO LOCAL STORAGE, we save current editor content as a string to local storage. We use convertToRaw and JSON.stringify for it:

 saveRaw = () => {
  var contentRaw = convertToRaw(this.state.editorState.getCurrentContent());

  localStorage.setItem('draftRaw', JSON.stringify(contentRaw));
}

If after that you reload the page, your editor will be initialized with the content and styles what you save. Becouse of in constructor we read the appropriate local storage property, and with JSON.parse, convertFromRaw and createWithContent methods initialize editor with the previously stored content.

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
  };
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!