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

Lexical基于光标位置为TextNode加下划线遇无限更新问题

问题:Lexical中根据光标位置给单词加下划线导致无限更新

我想实现的功能是:根据光标位置决定哪个TextNode添加下划线(效果类似示例中“are”被下划线标注,其余文字正常)。

我尝试通过以下方式实现:

  • 使用editor.registerNodeTransform将单个TextNode按空格拆分为多个TextNode
  • 通过editor.registerCommand(SELECTION_CHANGE_COMMAND)来设置下划线样式

但遇到了Lexical无限更新的问题,以下是我的代码示例:

import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext";
import { useEffect } from "react";
import { TextNode } from "lexical";
import {
  $getSelection,
  SELECTION_CHANGE_COMMAND,
  COMMAND_PRIORITY_NORMAL
} from "lexical";

export default function UnderlinePlugin() {
  const [editor] = useLexicalComposerContext();

  useEffect(() => {
    editor.registerNodeTransform(TextNode, (textNode) => {
      const textContent = textNode.getTextContent();

      const whiteSpaceIndices = [];
      for (let i = 0; i < textContent.length; i++) {
        if (textContent[i] === " ") {
          whiteSpaceIndices.push(i);
          whiteSpaceIndices.push(i + 1);
        }
      }

      editor.update(() => {
        textNode.splitText(...whiteSpaceIndices);
      });
    });
  }, []);

  useEffect(() => {
    return editor.registerCommand(
      SELECTION_CHANGE_COMMAND,
      () => {
        const selection = $getSelection();

        const [node] = selection.getNodes();

        // node.setFormat("underline"); // <- causes lexical to indefinitely update
      },
      COMMAND_PRIORITY_NORMAL
    );
  }, []);

  return null;
}

请问我哪里操作有误?🤔

内容的提问来源于stack exchange,提问作者feerlay

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 10:48:10