如何在react-draft-wysiwyg中用ContentState的JSON更新EditorState?
解决方案:在react-draft-wysiwyg中加载初始JSON内容
我来帮你搞定这个问题!要让编辑器渲染你预定义的JSON内容,关键是用Draft.js提供的EditorState.createWithContent()方法来初始化编辑器状态,而不是createEmpty()。下面是具体的修改步骤和完整代码:
核心思路
Draft.js的EditorState是不可变对象,不能直接修改,必须通过官方提供的方法来创建或更新。你已经把JSON数据转换成了ContentState,现在只需要用这个ContentState来创建对应的EditorState即可。
修改步骤
- 第一步:在组件构造函数中,用
EditorState.createWithContent(contentState)替代EditorState.createEmpty(),把转换后的内容传入。 - 第二步:确保编辑器组件正确绑定
editorState和对应的更新方法(如果需要处理编辑器内容变化,建议同时使用onEditorStateChange来维护完整的编辑器状态)。
完整修改后的代码
import React, { Component } from 'react'; import { EditorState, convertToRaw, convertFromRaw, ContentState } from 'draft-js'; import { Editor } from 'react-draft-wysiwyg'; // 你的示例JSON内容 const content = { "blocks":[{"key":"5ngeh","text":"hi there !!!!!","type":"unstyled","depth":0,"inlineStyleRanges":[],"entityRanges":[],"data":{}}], "entityMap":{} }; class BlogEdit extends Component { constructor(props) { super(props); // 把JSON转换成ContentState const contentState = convertFromRaw(content); // 用ContentState创建初始的EditorState const editorState = EditorState.createWithContent(contentState); this.state = { editorState, contentState }; // 绑定事件处理函数的this上下文 this.onEditorStateChange = this.onEditorStateChange.bind(this); this.onContentStateChange = this.onContentStateChange.bind(this); } // 处理EditorState变化(推荐使用,因为它包含光标、选中状态等完整编辑器信息) onEditorStateChange = (editorState) => { this.setState({ editorState }); }; // 处理ContentState变化(保留你原来的逻辑) onContentStateChange = (contentState) => { this.setState({ contentState }); }; render() { const { editorState } = this.state; return ( <div> <Editor editorState={editorState} wrapperClassName="demo-wrapper" editorClassName="demo-editor" onEditorStateChange={this.onEditorStateChange} onContentStateChange={this.onContentStateChange} /> </div> ); } } export default BlogEdit;
额外说明
EditorState包含了编辑器的完整状态(比如光标位置、选中内容等),而ContentState仅存储纯内容数据。建议在处理编辑器交互时优先使用onEditorStateChange来更新状态。- 如果你需要把编辑器内容导出为JSON,依然可以用
convertToRaw(this.state.contentState)或者convertToRaw(this.state.editorState.getCurrentContent())来实现。
内容的提问来源于stack exchange,提问作者quepayal
相关产品推荐
相关产品推荐

