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

WordPress Gutenberg嵌套块:父块如何访问并保存子块数据?

解决NestedBlock父块生成子块锚点导航的问题

你的代码核心问题

  1. save函数禁止调用编辑器状态方法:save是纯渲染函数,仅能使用传入的innerBlocks参数,select('core/block-editor').getBlocks()属于编辑器状态调用,会触发报错。
  2. 变量作用域冲突:if内部重新声明const anchorLinks,导致外部变量始终为空字符串,导航无法渲染。
  3. JSX语法不规范:map返回元素缺少唯一key,HTML原生class需替换为React的className,字符串拼接逻辑存在语法问题。

修正后的完整save函数

save: ({ attributes, innerBlocks }) => {
    const blockProps = useBlockProps.save();
    // 直接使用传入的innerBlocks生成导航
    const anchorLinks = innerBlocks.map((childBlock, index) => {
        const childUniqueId = childBlock.attributes.uniqueId;
        // 跳过无uniqueId的子块
        if (!childUniqueId) return null;
        
        return (
            <a 
                key={index}
                href={`#${childUniqueId}`}
                className="child-nav-link"
            >
                {childBlock.attributes.heading || `子块${index + 1}`}
            </a>
        );
    });

    return (
        <div {...blockProps}>
            {/* 用nav元素包裹锚点导航 */}
            <nav className="child-block-nav">
                {anchorLinks}
            </nav>
            <InnerBlocks.Content />
        </div>
    );
},

子块必须配置的内容

要让锚点生效,子块的根元素必须设置对应id,在子块的save函数中添加:

save: ({ attributes }) => {
    const blockProps = useBlockProps.save({
        id: attributes.uniqueId // 将子块的uniqueId设为根元素id
    });
    
    return (
        <div {...blockProps}>
            <h3>{attributes.heading}</h3>
            <div>{attributes.content}</div>
        </div>
    );
}

额外配置提示

  • 父块限制子块类型:在父块edit函数中锁定允许添加的子块
<InnerBlocks
    allowedBlocks={['your-plugin/child-block']} // 替换为你的子块名称
/>
  • 子块生成唯一ID:在子块attributes中定义自动生成的uniqueId
attributes: {
    uniqueId: {
        type: 'string',
        default: () => wp.utils.generateUUID()
    },
    heading: {
        type: 'string',
        source: 'html',
        selector: 'h3'
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 22:46:32