gpt4 book ai didi

reactjs - 无法将 Lexical 解析为 HTML

转载 作者:行者123 更新时间:2023-12-03 08:02:08 25 4
gpt4 key购买 nike

我有一个词法编辑器,需要将其序列化为 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().

我的编辑器组件采用一个 prop,即 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 issues我找到了一个与词法文档中的示例相反的解决方案。

需要将 $generateHtmlFromNodes 函数包装在 editor.update 函数中,如下所示:

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

关于reactjs - 无法将 Lexical 解析为 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73807767/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com