Draft js. Persist EditorContent to database

后端 未结 4 1769
南旧
南旧 2020-12-25 12:23

I\'m trying to persist draft-js\'s EditorContent to database then read and recreate the EditorContent object again. But EditorContent.getPla

4条回答
  •  庸人自扰
    2020-12-25 13:02

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

提交回复
热议问题