Gutenberg开发:如何基于Block数组渲染多组嵌套Block?
Got it, let's break this down. Since InnerBlocks is tied to the current block's native inner blocks context (and can only be used once per save function), we need a custom recursive renderer to handle your pre-stored nested block arrays. Here's how to make it work:
Core Approach
We'll build a reusable recursive function that loops through each block in your array, fetches the corresponding block type's save component, and renders it along with its nested inner blocks (by calling the same function recursively).
Step-by-Step Implementation
Create the Recursive Renderer Function
This function will take an array of blocks and return their fully rendered output:import { getBlockType } from '@wordpress/blocks'; import { createElement } from '@wordpress/element'; const renderBlocks = ( blocks ) => { if ( !blocks || !Array.isArray( blocks ) ) { return null; } return blocks.map( ( block ) => { // Skip invalid or unrecognized blocks if ( !block?.name || !block.isValid ) { return null; } const BlockType = getBlockType( block.name ); // Fallback if the block type isn't registered if ( !BlockType?.save ) { return null; } // Render the block's save component, passing attributes and rendered inner blocks return createElement( BlockType.save, { ...block.attributes, key: block.clientId, // Use unique clientId as React key }, // Recursively render nested inner blocks renderBlocks( block.innerBlocks ) ); } ); };Integrate the Renderer into Your Save Function
In your block'ssavemethod, call this function with your stored block array:export default function save( { attributes } ) { const { storedBlocks } = attributes; // Replace with your actual attribute name return ( <div className="your-custom-block-wrapper"> { renderBlocks( storedBlocks ) } </div> ); }
Key Details
- Recursion for Nesting: The function automatically handles any depth of nested blocks (like your columns → column → heading/paragraph/columns structure) by calling itself on each block's
innerBlocks. - Error Prevention: We add checks to skip invalid blocks and handle cases where a block type isn't registered, avoiding runtime errors.
- React Key Safety: Using the block's
clientIdas the React key ensures proper component re-rendering since each block has a unique identifier. - Compatibility: This works with both core Gutenberg blocks and custom blocks, as long as their save components are properly registered in the editor.
How It Works With Your Block Structure
For the nested array you shared, this renderer will:
- Start with the top-level
core/columnsblock, applying itsclassNameattribute. - Recursively render each inner
core/columnblock. - Inside each column, render the
core/heading,core/paragraph, and nestedcore/columnsblocks—continuing down the tree until all inner blocks are processed.
内容的提问来源于stack exchange,提问作者emir

