我正在使用高级自定义字段 (ACF) 为 WordPress Gutenberg 编辑器创建自定义块。我设计了一个名为“Tabs”的父块,它可以包含多个内部块,每个内部块名为“Tab”。
这是我想要实现的目标的简单表示:
// Parent Block: Tabs (render.php file)
<Tabs>
<InnerBlocks />
</Tabs>
// InnerBlock: Tab (render.php file)
// Inside this block, I need to access the ID of the parent (Tabs)
// and also the current index or position of this inner block (Tab).
我的挑战是访问:
鉴于我正在使用 ACF 来创建块,我如何在自定义块的
render.php
文件中检索此信息?
有没有人做过类似的事情或者可以指导我完成这个?
也许不是更好的解决方案,但有一个方法 在您的 Tab.tsx 中,您可以添加以下内容:
const index = select('core/block-editor').getBlockIndex(props.clientId);
useEffect(() => {
setAttributes({ index });
}, [index, setAttributes]);
当然你注册组件的时候需要添加索引属性
对于父 ID,下面是获取父上下文的方法
const parentClientId = select(
'core/block-editor',
).getBlockHierarchyRootClientId(props.clientId);
const parentAttributes = select('core/block-editor').getBlock(parentClientId);
您还有另一种方法可以探索,那就是向 Tabs.tsx 添加上下文
registerBlockType('stackoverflow/tabs', {
title: 'tabs',
description: 'tabs',
category: 'widgets',
attributes: {
id: { type: 'string' },
},
providesContext: {
id: 'id',
},
edit: YourEditFile,
save: YourSaveFile,
});
并在 Tab.tsx 中恢复上下文
registerBlockType('stackoverflow/tab', {
usesContext: ['id'],
});
要在 Tab.tsx 中阅读它,您可以执行以下操作
const { id } = props.context;