首页 文章

如何在react-draft-wysiwyg中从ContentState的给定JSON数据更新Editor状态?

提问于
浏览
0

这是我的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;

那么我应该做什么呢?

2 回答

  • 1

    编辑器组件具有道具名称 initialContentState . 您可以在此处传递内容状态 .

  • 1

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

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

    您可能需要阅读该文档,它具有很好的解释 .

相关问题