WordPress Gutenberg嵌套块:父块如何访问并保存子块数据?
解决NestedBlock父块生成子块锚点导航的问题
你的代码核心问题
- save函数禁止调用编辑器状态方法:save是纯渲染函数,仅能使用传入的
innerBlocks参数,select('core/block-editor').getBlocks()属于编辑器状态调用,会触发报错。 - 变量作用域冲突:if内部重新声明
const anchorLinks,导致外部变量始终为空字符串,导航无法渲染。 - 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
相关产品推荐
相关产品推荐

