You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 19:33:30