首页 文章

react-draft-wysiwyg - 渲染已保存的内容以进行更新

提问于
浏览
0

我在一个项目中使用react-draft-wysiwyg并且我遇到了大问题 .

经过几个小时的尝试,我无法渲染数据库的内容 .

首先,我尝试使用以下代码在MongoDB中成功保存“overview”(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,}};

正如您所看到的,我没有在构造函数中设置:{overview:{}},因为如果我这样做,我会收到以下错误:

无效的RawDraftContentState▶折叠了24个堆栈帧 . ./src/index.js src / index.js:19 16 | ); 17 | 18 | 19 | ReactDOM.render(20 | 21 | 22 |,

所以我只是不在构造函数中设置概述:{}和 the saving process is working correctly.

之后,我正在尝试在组件中呈现已保存的内容,以便能够进行更改和更新 . 如果我可以使用相同的组件进行编辑和保存以使其可重用,那将是很好的,但它不是必须的 .

问题是虽然我设置了this.setState({person:overview:contentFromDatabase})(选中,它正在被设置),但该组件显示为空白,没有 . 你可以从零开始写,但它没有加载内容 .

我不得不说现在几小时后我对editorState和contentState的东西感到困惑,但我认为我的DB的内容是RawDraftContent,对吧?

这是我的DB文件:

"_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 }

我们将非常感激地提供任何帮助 .

2 回答

  • 0

    而不是将数据库中的内容保存为编辑器状态,您可以执行以下操作:

    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,
            ),
          };
    }
    
  • 0

    最后使用editorContent convertToRaw convertFrom raw完成 .

相关问题