wordpress 如何在 gutenberg 自定义块中访问当前内部块的父块ID和索引?

qfe3c7zg  于 5个月前  发布在  WordPress
关注(0)|答案(1)|浏览(56)

我正在使用高级自定义字段(ACF)为WordPress gutenberg 编辑器创建自定义块。我设计了一个名为“选项卡”的父块,它可以包含多个内部块,每个块都命名为“选项卡”。
下面是我试图实现的一个简单表示:

// 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).

字符串
我的挑战是访问:
1.每个Tab内部块中的父块(Tab)的ID。

  1. Tab内部块在内部块本身中的当前索引或位置。
    假设我使用ACF创建块,我如何在自定义块的render.php文件中检索此信息?
    有没有人做过类似的工作,或者可以指导我完成这件事?
bis0qfac

bis0qfac1#

索引

也许不是更好的解决方案,但有一种方法在您的Tab.tsx中,您可以添加:

const index = select('core/block-editor').getBlockIndex(props.clientId);

  useEffect(() => {
    setAttributes({ index });
  }, [index, setAttributes]);

字符串
当然,在注册组件时,需要添加索引属性

父Id

对于父ID,下面是一种获取父上下文的方法

const parentClientId = select(
    'core/block-editor',
  ).getBlockHierarchyRootClientId(props.clientId);
  const parentAttributes = select('core/block-editor').getBlock(parentClientId);

父ID #2

还有另一种方法可以探索,那就是向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;

相关问题