最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

block editor - Gutenburg InnerBlock single child

programmeradmin1浏览0评论

I have a custom block called Custom Card that takes an InnerBlock as a child. The purpose of this is because I want to format the content within the Custom Card a very specific way.

The Custom Card has three allowed blocks:

  • core/quote
  • core/video
  • core/image

The problem I've run into, is that after a user selects a block they can continue to add more blocks to the same Card. I want to limit the card to allow them to select one of the three options they have available. What is some ways I can go about doing this?

I have a custom block called Custom Card that takes an InnerBlock as a child. The purpose of this is because I want to format the content within the Custom Card a very specific way.

The Custom Card has three allowed blocks:

  • core/quote
  • core/video
  • core/image

The problem I've run into, is that after a user selects a block they can continue to add more blocks to the same Card. I want to limit the card to allow them to select one of the three options they have available. What is some ways I can go about doing this?

Share Improve this question asked Oct 11, 2019 at 21:14 ZacharyZachary 1581 silver badge9 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 2

Here is a simple solution to this problem I've implemented using the renderAppender prop, inspired by Welcher's comment above and this post over on Stack.

<InnerBlocks
  renderAppender={() => {
    const blocks = select('core/editor').getBlocks();
    const block = find(blocks, ['name', 'NAME_OF_YOUR_BLOCK']);
    // don't return appender if there's one or more blocks:
    if (block && block.innerBlocks.length > 0) return null;
    // otherwise, return default appender
    return (<InnerBlocks.DefaultBlockAppender />);
  }}
/>

Note: This example is using lodash find function to get the block I'm targeting. There may be a better way to do this, but for now it does the job.

Also, be sure to import the select function. E.g.

import { select } from '@wordpress/data';

The only way to do this at the moment is by using the renderAppenderprop onInnerBlocks. This prop is only available in the Gutenberg plugin until WordPress 5.3 is released. The theory would be to use state in each CustomCard to track if there has been a block added, then return false from the renderAppender function so the user cannot insert more items.

发布评论

评论列表(0)

  1. 暂无评论