这是我第一次在 stackoverflow 上提问,但我在这个问题上被困了太多天了。
我的问题,如何将initialConfig.editorState更改为我刚刚保存在数据库中的stringifiedEditorState?
到目前为止,我正在使用 Lexical,这是一个带有 React/Next.js 的 Facebook 文本编辑器。我能够创建一个编辑器并将其作为 JSON 字符串保存到我的 mongodb 数据库中。
{
"root": {
"children": [
{
"children": [
{ "detail": 0, "format": 1, "mode": "normal", "style": "", "text": "Test", "type": "text", "version": 1 }
],
"direction": "ltr",
"format": "",
"indent": 0,
"type": "paragraph",
"version": 1
}
],
"direction": "ltr",
"format": "",
"indent": 0,
"type": "root",
"version": 1
}
}
我希望能够使用新的只读词法编辑器读取保存到 mongodb 数据库的 Json 值。
function onChange(editorState: any) {
editorState.read(() => {
const stringifiedEditorState = JSON.stringify(editorState.toJSON());
setValue(stringifiedEditorState);
});
}
const initialConfig = {
namespace: "editeurConfig",
theme: editeurTheme,
onError: onError,
nodes: [ListNode, ListItemNode, AutoLinkNode, LinkNode],
readOnly: true,
editorState: null
};
我的问题又来了,如何将initialConfig.editorState更改为我刚刚保存在数据库中的stringifiedEditorState?
最佳答案
编辑器初始化
您只需通过 editorState
键将序列化字符串传递到编辑器的初始状态即可。
例如:
// your config
const editorConfig = {
// the rest of your config...
editorState: editorStateJSONString,
};
// inside your return statement
<LexicalComposer initialConfig={editorConfig}>
{/* Your plugins */}
</LexicalComposer>
需要注意的是:
Note that Lexical uses initialConfig.editorState only once (when it's being initialized) and passing different value later won't be reflected in editor
来自:https://lexical.dev/docs/concepts/editor-state
所以这取决于初始化编辑器的时间和检索数据库数据的时间。
编辑器初始化后
看来您可以使用setEditorState
在初始化后更新状态:
Another way to set state is setEditorState method, which replaces current state with the one passed as an argument.
例如:
const editorState = editor.parseEditorState(editorStateJSONString);
editor.setEditorState(editorState);
来自:https://lexical.dev/docs/concepts/editor-state#updating-state
关于reactjs - 将词汇数据发送到服务器并使用新的词汇组件读取它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73042976/