React项目中Lexical Editor文本内容的获取与修改问题
React项目中如何将音频转写API文本传入Lexical Editor
我在React项目中使用Lexical Editor,从音频转写API获取文本后,需要将其传入Lexical Editor,但不清楚如何操作文本,遇到了实现难题。此前使用普通TextArea时,我直接通过如下方式传递文本:
<TextEditor value={transcription} readOnly={editorState} /> // transcription为API返回的转写文本
但这套方式在Lexical Editor里行不通,我查阅了官方文档仍未解决问题。以下是我的TextEditor.tsx代码:
import { useEffect } from "react"; import { LexicalComposer } from "@lexical/react/LexicalComposer"; import { RichTextPlugin } from "@lexical/react/LexicalRichTextPlugin"; import { ContentEditable } from "@lexical/react/LexicalContentEditable"; import { HistoryPlugin } from "@lexical/react/LexicalHistoryPlugin"; import { ListPlugin } from "@lexical/react/LexicalListPlugin"; import { EditorState } from "lexical"; import { LexicalErrorBoundary } from "@lexical/react/LexicalErrorBoundary"; import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext"; import { HeadingNode } from "@lexical/rich-text"; import { ListNode, ListItemNode } from '@lexical/list'; import { ToolBarPlugin } from "./Toolbar"; interface TextEditorProps { value: string; readOnly: boolean; } const theme = { // apenas css | exemplo: // heading: { // h1: "classe-do-h1" // } // importa arquivo css com os estilos }; function onError(error: Error): void { console.error(error); } const MyOnChangePuglin = (props: { onChange: (editorState: EditorState) => void }): null => { const [editor] = useLexicalComposerContext(); const { onChange } = props; useEffect(() => { return editor.registerUpdateListener(({ editorState }) => { onChange(editorState); }); }, [onChange, editor]); return null; }; export function TextEditor({ value, readOnly }: TextEditorProps) { const initialConfig = { namespace: "MyEditor", theme, onError, nodes: [HeadingNode, ListNode, ListItemNode] }; return ( <LexicalComposer initialConfig={initialConfig}> <ToolBarPlugin /> <ListPlugin /> <RichTextPlugin contentEditable={ <ContentEditable className={`min-h-[500px] border-[1px] border-[#d4d4d4] p-4 rounded-md shadow-lg bg-[#f8f8f8] overflow-y-auto focus:outline-none ${ readOnly ? "cursor-not-allowed" : "cursor-text" }`} /> } ErrorBoundary={LexicalErrorBoundary} /> <MyOnChangePuglin onChange={(editorState) => console.log(editorState._nodeMap)} /> <HistoryPlugin /> </LexicalComposer> ); }
内容的提问来源于stack exchange,提问作者Vicenzo Frusciante
相关产品推荐
相关产品推荐

