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

无需使用List区块即可为自定义Gutenberg区块添加列表格式化功能

自定义Gutenberg区块添加工具栏列表格式化实现方案

核心实现逻辑

不需要将自定义区块改造为InnerBlock架构,直接基于Gutenberg内置的RichText组件的格式扩展能力即可实现,列表格式化和粗体、斜体属于同级别格式类型,可直接配置到工具栏。

具体实现步骤

1. 配置RichText组件允许的格式

在你自定义区块的edit方法中,找到承载内容的RichText组件,在allowedFormats属性中加入两个内置的列表格式:

  • 无序列表:core/bulleted-list
  • 有序列表:core/numbered-list

代码示例:

import { RichText } from '@wordpress/block-editor';
import { __ } from '@wordpress/i18n';

// edit函数内的RichText调用示例
<RichText
    tagName="div" // 注意不要使用p标签,p标签无法嵌套列表元素
    value={ attributes.content }
    onChange={ ( newContent ) => setAttributes( { content: newContent } ) }
    allowedFormats={ [
        'core/bold',
        'core/italic',
        'core/link',
        'core/bulleted-list',
        'core/numbered-list'
        // 可按需添加其他所需内置格式
    ] }
    placeholder={ __( '请输入内容', 'your-plugin-domain' ) }
/>

2. 配置save输出逻辑

保存阶段直接使用RichText.Content输出内容,内置会自动保留列表的HTML结构,无需额外处理:

// save函数示例
import { RichText } from '@wordpress/block-editor';

export default function save( { attributes } ) {
    return (
        <RichText.Content
            tagName="div"
            value={ attributes.content }
        />
    );
}

可选方案:自定义列表格式

如果需要修改列表按钮的样式、交互逻辑,或者使用的Gutenberg版本过低没有内置列表格式,可以通过registerFormatType手动注册自定义格式,实现完全可控的列表格式化能力。
代码示例:

import { registerFormatType, toggleList } from '@wordpress/rich-text';
import { RichTextToolbarButton } from '@wordpress/block-editor';
import { listUl, listOl } from '@wordpress/icons';
import { __ } from '@wordpress/i18n';

// 注册无序列表格式
registerFormatType( 'your-plugin/bulleted-list', {
    title: __( '无序列表', 'your-plugin-domain' ),
    tagName: 'ul',
    className: 'custom-bulleted-list',
    edit: ( { isActive, value, onChange } ) => {
        return (
            <RichTextToolbarButton
                icon={ listUl }
                isActive={ isActive }
                onClick={ () => onChange( toggleList( value, 'ul' ) ) }
            />
        );
    },
} );

// 有序列表注册逻辑同上,替换tagName为ol、icon为listOl即可

注册完成后将自定义的格式ID加入RichText的allowedFormats数组即可使用。

注意事项

  • 不要将RichText的tagName设置为<p>标签,<p>标签不支持嵌套<ul>/<ol>元素,会导致前端渲染时列表结构异常
  • 如果开启了内容格式过滤,需要确保<ul>、<ol>、<li>标签在允许的HTML标签范围内,避免列表被过滤

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 19:18:00