簡體   English   中英

react-draft-wysiwyg - 渲染保存的內容以更新

[英]react-draft-wysiwyg - render saved content to update

我在一個項目中使用react-draft-wysiwyg ,我遇到了一個“大”問題。

經過數小時的嘗試,我無法渲染我的數據庫內容。

首先,我嘗試使用以下代碼成功地在 MongoDB 中保存了“概述”(contentState):

 <Editor initialContentState={person.overview}
         toolbarClassName="rdw-storybook-toolbar"
         wrapperClassName="rdw-storybook-wrapper"
         editorClassName="editor" onContentStateChange={this.onContentStateChange}
         toolbar={{ options: [
                         'inline',
                         'blockType',
                         'fontSize',
                         'fontFamily',
                         'list',
                         'textAlign',
                         'colorPicker',
                         'link',
                         'embedded',
                         'emoji',
                         'remove',
                         'history'], 
                        }}

我的組件構造函數:

this.state = { person: { isEdit: false, } };

如您所見,我沒有在構造函數中設置 person: {overview: {} },因為如果我這樣做,我會收到以下錯誤:

無效的 RawDraftContentState ▶ 24 個堆棧幀已折疊。 ./src/index.js src/index.js:19 16 | ); 17 | 18 | 19 | ReactDOM.render( 20 | 21 | 22 | ,

所以我只是沒有在構造函數中設置概覽:{} 並且保存過程正常工作。

之后,我嘗試在組件中呈現保存的內容,以便能夠進行更改和更新。 如果我可以使用相同的組件進行編輯和保存以使其可重用,那就太好了,但這不是必須的。

問題是,雖然我設置了 this.setState({person:overview: contentFromDatabase})(已檢查,正在設置),但組件顯示為空白,什么都沒有。 您可以從零開始寫入,但不會加載內容。

我不得不說,現在幾個小時后我對 editorState 和 contentState 的東西有點困惑,但我認為我的數據庫的內容是一個 RawDraftContent,對吧?

這是我的數據庫文件:

    "_id": ObjectId("5b3d2897589a5e2fa4ba60ea"),
    "overview": {
      "blocks": [
        {
          "key": "ekrl0",
          "text": "this is the CONTENT",
          "type": "unstyled",
          "depth": 0,
          "inlineStyleRanges": [
            {
              "offset": 14,
              "length": 2,
              "style": "BOLD"
            }
          ],
          "entityRanges": []
        }
      ]
    },
    "createdAt": ISODate("2018-07-04T20:05:43.129Z"),
    "__v": 0
  }

任何幫助將不勝感激。

您可以執行以下操作,而不是將 DB 中的內容保存為編輯器狀態:

import {
  Editor,
  EditorState,
  ContentState,
  convertFromHTML,
  CompositeDecorator,
  convertToRaw,
  getDefaultKeyBinding,
} from 'draft-js';

const blocks = convertToRaw(editorState.getCurrentContent()).blocks;
    const value = blocks.map(block => (!block.text.trim() && '\n') || block.text).join('\n');

為了檢索數據,您可以執行以下操作:

componentWillMount() { 
      const { value } = this.props
      const blocksFromHTML = convertFromHTML(value));
      const state = ContentState.createFromBlockArray(
        blocksFromHTML.contentBlocks,
        blocksFromHTML.entityMap,
      );
      this.state = {
        editorState: EditorState.createWithContent(
          state,
          compositeDecorator,
        ),
      };
}

最后使用 editorContent + convertToRaw + convertFrom raw 完成。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM