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

如何通过按钮点击在Lexical编辑器选中位置后插入自定义样式文本?

在Lexical Editor中通过按钮插入自定义样式文本到选中位置后方

核心实现思路

Lexical Editor的状态修改必须通过editor.update()完成,我们需要在按钮点击事件中:

  1. 获取当前选中位置的末尾节点与偏移量
  2. 创建带有自定义样式的文本节点
  3. 将节点插入到选中位置后方,并调整光标位置

步骤1:定义自定义样式

先在全局样式中添加自定义类的样式:

.custom-style {
  background: #e6f7ff;
  padding: 2px 6px;
  border-radius: 4px;
  font-weight: 500;
  color: #1890ff;
}

步骤2:编写插入函数

创建处理按钮点击的核心函数,利用Lexical内部API完成节点插入:

import { $getSelection, TextNode } from 'lexical';

/**
 * 在选中位置后方插入带自定义样式的文本
 * @param {Editor} editor - Lexical编辑器实例
 * @param {string} text - 要插入的文本内容,默认值为'MyFriendName'
 */
const insertStyledText = (editor, text = 'MyFriendName') => {
  editor.update(() => {
    const selection = $getSelection();
    if (!selection) return;

    // 获取选中范围的末尾位置
    const range = selection.getRange();
    const endNode = range.end.node;
    const endOffset = range.end.offset;

    // 创建带自定义样式的文本节点
    const styledTextNode = new TextNode(text);
    // 关联自定义样式类(需确保编辑器配置支持该格式)
    styledTextNode.setFormat('custom-style');

    // 根据末尾节点类型处理插入逻辑
    if (endNode.isTextNode()) {
      // 拆分文本节点,在选中位置后方插入新节点
      const splitNode = endNode.splitText(endOffset);
      splitNode.insertBefore(styledTextNode);
    } else {
      // 若末尾是块级节点,直接在节点后方插入
      endNode.insertAfter(styledTextNode);
    }

    // 将光标移动到新插入文本的后方
    selection.setRange(
      styledTextNode,
      text.length,
      styledTextNode,
      text.length
    );
  });
};

步骤3:配置编辑器支持自定义格式

初始化Lexical编辑器时,注册自定义格式以关联对应的CSS类:

import { createEditor } from 'lexical';

const editor = createEditor({
  nodes: [
    {
      name: 'custom-style',
      type: TextNode,
      format: 'custom-style',
      className: 'custom-style',
      // 可选:添加序列化规则,确保HTML导出时保留样式
      exportDOM: (node) => {
        const span = document.createElement('span');
        span.className = 'custom-style';
        span.textContent = node.getTextContent();
        return { element: span };
      },
    },
  ],
});

步骤4:绑定按钮点击事件

在React组件中使用按钮触发插入函数:

<button onClick={() => insertStyledText(editor, 'MyFriendName')}>
  插入好友标签
</button>

与Hashtag插件的逻辑关联

你参考的Hashtag插件核心是监听输入并自动转换节点,而本次需求是主动触发节点插入,两者的共性在于:

  • 都需要创建带自定义样式的文本节点
  • 都依赖Lexical的editor.update()修改状态
  • 都需要处理节点插入的位置计算

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 03:26:11