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

如何在Payload CMS的Lexical编辑器中添加富文本与HTML切换功能?

Payload CMS Lexical富文本编辑器:HTML源码切换与元素ID配置方案

问题描述

我在Next.js项目中集成了Payload CMS,使用Lexical富文本编辑器字段,配置如下:

{
  name: 'content',
  type: 'richText',
  editor: lexicalEditor({
    features: ({ rootFeatures }) => [
      ...rootFeatures,
      // 自定义扩展
    ],
  }),
  // 其他配置
}

导入语句:

import { lexicalEditor } from '@payloadcms/richtext-lexical';

当前有两个需求:

  1. 给编辑器中的元素(如标题)添加ID,生成带哈希值的目录锚点链接;
  2. 实现类似Hubspot的富文本/HTML源码模式切换编辑功能。
    已知该字段默认输出JSON结构,是否需要配置适配器处理HTML转换?Payload能否实现HTML源码编辑?

解决方案

一、给元素添加ID(无需切换HTML模式)

推荐直接扩展Lexical节点实现ID配置,更符合编辑器的JSON结构设计:

  1. 自定义Heading节点插件,添加ID输入字段:
import { HeadingNode } from '@lexical/rich-text';
import { createPlugin } from '@payloadcms/richtext-lexical';

const CustomHeadingWithID = createPlugin({
  nodes: [
    {
      ...HeadingNode,
      // 给节点添加ID属性
      addExtraAttributes: () => ({
        id: '',
      }),
      // 自定义编辑器内的设置面板,添加ID输入框
      Edit: ({ node, onChange }) => {
        return (
          <input
            type="text"
            value={node.__data.id || ''}
            onChange={(e) => onChange({ ...node, __data: { ...node.__data, id: e.target.value } })}
            placeholder="设置锚点ID"
            style={{ marginTop: '8px', padding: '4px' }}
          />
        );
      },
    },
  ],
});
  1. 将插件加入编辑器配置:
editor: lexicalEditor({
  features: ({ rootFeatures }) => [
    ...rootFeatures,
    CustomHeadingWithID,
  ],
}),
  1. 前端渲染时,renderLexical组件会自动将ID属性注入对应的HTML标签,直接生成#xxx格式的锚点链接。

二、实现富文本/HTML源码切换

Payload的Lexical编辑器默认无此功能,可通过两种方式实现:

  1. 自定义插件开发切换功能

    • 利用Lexical的$generateHtmlFromNodes将JSON内容转为HTML,用$parseHtml将HTML转回Lexical节点;
    • 在编辑器工具栏添加切换按钮,点击时在富文本视图与textarea HTML编辑视图之间切换;
    • 注意处理转换兼容性,避免样式或结构丢失(比如部分Lexical独有格式无法转成标准HTML)。
  2. 新增独立HTML字段(临时方案)

    • 在集合中添加contentHtml字段,类型设为textarea,允许用户手动编辑HTML;
    • 需自行通过Payload hooks处理富文本与HTML字段的同步逻辑,缺点是容易出现格式不一致,仅适合临时需求。

三、JSON转HTML的处理

无需在后台配置适配器,前端直接处理即可:

  • 使用Payload官方组件渲染:
import { renderLexical } from '@payloadcms/richtext-lexical/react';

// 组件内渲染
<div className="content">{renderLexical({ content: post.content })}</div>
  • 手动转换HTML:
import { generateHtmlFromNodes } from '@lexical/html';
import { createEditor, EditorState } from 'lexical';

const editor = createEditor();
const htmlContent = generateHtmlFromNodes(editor, EditorState.create(post.content));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 04:52:06