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
相关产品推荐
相关产品推荐

