【问题标题】:How to update Editor state from given JSON data of ContentState in react-draft-wysiwyg?如何从 react-draft-wysiwyg 中的 ContentState 的给定 JSON 数据更新编辑器状态?
【发布时间】:2018-05-20 11:10:55
【问题描述】:

这是我的 editor.js

我在 const 内容中有示例 JSON 数据。 我想要做的是,最初当我打开我的编辑器时,它应该在变量内容中呈现初始内容。 但我不知道如何更新 editorState,因为它是不可变的。

import React, { Component } from 'react';
import { EditorState, convertToRaw, convertFromRaw, ContentState } from 'draft-js';
import { Editor } from 'react-draft-wysiwyg';


const content = {"blocks":[{"key":"5ngeh","text":"hi there !!!!!","type":"unstyled","depth":0,"inlineStyleRanges":[],"entityRanges":[],"data":{}}],"entityMap":{}};

这是我的 BlogEdit 组件:

class BlogEdit extends Component {
constructor(props) {
    super(props);
    const contentState = convertFromRaw(content);
    console.log(contentState);
    this.state = {
    editorState: EditorState.createEmpty(),       //I need to change this to actually render the content of content variable in editor
    contentState,
    }
    console.log(contentState);
}

该函数负责根据editorState改变内容中的JSON

onContentStateChange: Function = (contentState) => {
    this.setState({
    contentState,
    });
};

这是渲染部分...

render() {
    const { editorState } = this.state;
    const { contentState } = this.state;
    return (
    <div>
        <Editor
        editorState={editorState}
        wrapperClassName="demo-wrapper"
        editorClassName="demo-editor"
        onContentStateChange={this.onContentStateChange}
        />

    </div>
    );
}
}

export default BlogEdit;

那么我到底应该怎么做呢?

【问题讨论】:

    标签: reactjs draftjs draft-js-plugins


    【解决方案1】:

    编辑器组件有一个道具名称initialContentState。你可以在这里传递内容状态。

    【讨论】:

      【解决方案2】:

      您可以使用内容创建,而不是 EditorState.createEmpty()

       let editorStatewithContent = EditorState.createWithContent(contentState);     
       //Then you set the state 
       this.state = {
         editorState:  editorStatewithContent      
      }
      

      您可能需要仔细阅读该文档,它对所有内容都进行了很好的解释。

      【讨论】:

      • 但它会杀死其他状态,如选择或撤消/重做堆栈
      【解决方案3】:

      如果你在使用 redux 并且你的编辑器状态没有 entityMap 对象,它会抛出一个错误。

      所以你可以这样做

      const content = convertFromRaw({...contentState, entityMap: {}})
      

      也能解决你invalid RawDraftContentState的问题

      无需设置任何initialContentState,无需设置该值即可实现

      this.setState({
          editorState: EditorState.createWithContent(content)
      })
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-12-30
        • 1970-01-01
        • 2021-11-11
        • 1970-01-01
        • 2021-11-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多