无法将词法分析为HTML



我有一个词法编辑器,需要将其序列化为html,以便将其嵌入到电子邮件模板中。

在使用$generateHtmlFromNodes功能时,我一直遇到以下错误:

Error: Unable to find an active editor state.
State helpers or node methods can only be
used synchronously during the callback of editor.update() or editorState.read().

我的Editor组件使用一个道具,LexicalEditor类型的editorRef,它确保我可以从父级访问编辑器,我想在父级处理序列化和发送电子邮件。

编辑器.tsx:

interface EditorProps {
editorRef: React.MutableRefObject<LexicalEditor>;
}
export const Editor = (props: EditorProps) => {
const initialConfig = {
namespace: 'MyEditor',
editable: true,
nodes: [ImageNode],
theme: <myTheme>,
onError(error) {
throw error;
},
};
return (
<div className="relative rounded-sm border border-gray-200 bg-white shadow-sm">
<LexicalComposer initialConfig={initialConfig}>
<Toolbar />
<ImagesPlugin />
<RichTextPlugin
contentEditable={
<ContentEditable
autoCorrect
className="min-h-[450px] resize-none overflow-hidden text-ellipsis py-[15px] px-2.5 outline-none"
/>
}
placeholder={null}
/>
<OnChangePlugin
onChange={(editorState, editor) => (props.editorRef.current = editor)}
/>
<HistoryPlugin />
</LexicalComposer>
</div>
);
};

我的父组件:


export default function EmailClient() {
const editorRef = useRef<LexicalEditor>();
const handleSendEmail = () => {
const editor = editorRef.current;
const editorState = editor.getEditorState();
const jsonString = JSON.stringify(editorState);
console.log('jsonString', jsonString);
const htmlString = $generateHtmlFromNodes(editor, null);
console.log(htmlString);
};
return (
<Editor editorRef={editorRef} />
<Button
text="send"
function={handleSendEmail}
/>
);
}

在深入研究Github问题后,我找到了一个与词法文档中的示例相反的解决方案。

有必要将$generateHtmlFromNodes函数封装在editor.update函数中,如下所示:

editor.update(() => {
const htmlString = $generateHtmlFromNodes(editor, null);
});

最新更新