1

这是我的 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 改变 content 中的 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;

那么实际上我应该怎么做呢?

4

3 回答 3

2

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

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

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

于 2018-06-27T16:05:30.957 回答
2

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

于 2018-06-17T04:06:33.193 回答
0

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

所以你可以这样做

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

它也将解决您的问题invalid RawDraftContentState

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

this.setState({
    editorState: EditorState.createWithContent(content)
})
于 2020-06-05T22:53:54.900 回答