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

如何将含RichText多行属性的自定义Gutenberg块改为使用InnerBlocks?

解决Gutenberg RichText multiline属性弃用问题:改用InnerBlocks替代

控制台提示wp.blockEditor.RichText multiline自6.1版本弃用,6.3版本将彻底移除,要求改用嵌套块(InnerBlocks)。以下是把带multiline属性的RichText组件转换为InnerBlocks结构的具体步骤,完全保留原有功能:

1. 清理旧属性

原块用blurb属性存储富文本内容,改用InnerBlocks后内容由嵌套块管理,直接从块的attributes定义中删除blurb字段。

2. 重写edit函数

替换RichText为InnerBlocks,通过配置模板、允许的块类型实现原有功能:

import { InnerBlocks, useBlockProps } from '@wordpress/block-editor';
import { __ } from '@wordpress/i18n';

edit: ( props ) => {
    const blockProps = useBlockProps( { className: 'custom-cta p-0 mb-0' } );

    // 定义InnerBlocks模板:匹配原RichText的配置
    const BLOCK_TEMPLATE = [
        [
            'core/paragraph',
            {
                placeholder: __( 'Subtext goes here (optional)', 'hello-tools' ),
                allowedFormats: [ 'core/bold', 'core/italic' ],
                className: 'custom-cta__blurb w-100'
            }
        ]
    ];

    return (
        <div { ...blockProps }>
            <InnerBlocks
                template={ BLOCK_TEMPLATE }
                allowedBlocks={ [ 'core/paragraph' ] } // 仅允许段落块,对应原multiline="p"
                templateLock="all" // 锁定模板,仅可编辑内容(需允许多段落则改为"insert")
            />
        </div>
    );
}
  • template:初始化一个带占位符、格式限制和类名的段落块,完全对齐原RichText的配置
  • allowedBlocks:限制只能添加段落块,避免用户插入其他类型块
  • templateLock:all表示只能编辑现有段落内容,不能添加/删除块;如果原multiline允许多行输入,改成insert即可允许添加更多段落

3. 更新save函数

原save函数渲染blurb内容,现在替换为InnerBlocks的内容渲染:

import { InnerBlocks, useBlockProps } from '@wordpress/block-editor';

save: ( props ) => {
    const blockProps = useBlockProps.save( { className: 'custom-cta p-0 mb-0' } );
    return (
        <div { ...blockProps }>
            <InnerBlocks.Content />
        </div>
    );
}

4. 数据迁移(关键步骤)

旧块的内容存在blurb属性中,需自动转换为InnerBlocks的嵌套段落块,添加migrate函数:

import { createBlock } from '@wordpress/blocks';

migrate: ( attributes, innerBlocks ) => {
    // 检测到旧blurb内容且无嵌套块时,自动转换
    if ( attributes.blurb && innerBlocks.length === 0 ) {
        return {
            ...attributes,
            blurb: undefined, // 移除旧属性
            innerBlocks: [
                createBlock( 'core/paragraph', {
                    content: attributes.blurb,
                    className: 'custom-cta__blurb w-100'
                } )
            ]
        };
    }
    return { ...attributes, innerBlocks };
}

5. 样式兼容

原custom-cta__blurb类名已通过模板添加到段落块上,原有样式无需修改即可正常生效。

经过以上修改,块的功能和原multiline RichText完全一致,同时符合Gutenberg的最新规范,不会再出现弃用提示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 20:45:27