如何访问古腾堡自定义块中当前内块的父块ID和索引?

问题描述 投票:0回答:1

我正在使用高级自定义字段 (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).

我的挑战是访问:

  1. 每个选项卡内部块内部的父块(选项卡)的 ID。
  2. Tab 内块的当前索引或位置 内部块本身。

鉴于我正在使用 ACF 来创建块,我如何在自定义块的

render.php
文件中检索此信息?

有没有人做过类似的事情或者可以指导我完成这个?

php wordpress wordpress-gutenberg gutenberg-blocks acf-gutenberg
1个回答
0
投票

索引

也许不是更好的解决方案,但有一个方法 在您的 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);

家长 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;
© www.soinside.com 2019 - 2024. All rights reserved.