javascript - 无法在 ReactJs 中的服务器上使用 editorState 为 DraftJs 更新状态
问题描述
我已经在 DraftJs 的支持下实现了一个富文本编辑器来 React。
在转换为原始数据并将其字符串化后,我将 editorState 数据发送到服务器。这很适合将其渲染到前端。
现在,我想获取这些数据并用这些数据更新 editorState。因此,用户可以使用可用数据编辑文本。
我没有,为什么它不起作用。请帮我。我没有得到我应该做什么。
我的代码:导入依赖项
import { Editor } from "react-draft-wysiwyg";
import { EditorState, ContentState, convertFromRaw, convertToRaw } from "draft-js";
import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";
初始状态:
const [editorState, setEditorState] = useState(() =>
EditorState.createEmpty()
);
尝试编辑:
setEvent(current);
const data = JSON.parse(current.description);
// EditorState.createWithContent(convertFromRaw(data));
setEditorState(EditorState.createWithContent(ContentState.createFromText('Hello world')));
// EditorState.createWithContent(convertFromRaw(JSON.parse(current.description)));
// convertToRaw(JSON.parse(editorState.getCurrentContent()));
// const state = current.description;
// As per draft.js docs, I didn't understand the syntax
// convertFromRaw(rawState: state): ContentState
// EditorState.createWithContent(JSON.parse(current.description));
// setEditorState(JSON.parse(current.description));
尝试了所有这些东西。但是,没有任何更新editorState
到current.description
. 注意:current.description
是一个包含原始对象数据的 JSON 字符串。
解决方案
我已经解决了这个问题。DraftJs 官方文档有点混乱。它应该有一些例子。因此,初学者和中级开发人员都可以得到它。
我已经这样做了:
setEditorState(EditorState.createWithContent(convertFromRaw(JSON.parse(current.description))));
我希望我的努力能对别人有所帮助,他们不需要像我一样浪费时间。