来自块数组的渲染块-古登堡

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

我需要以某种方式从使用以下功能获得的块列表中渲染块:

const applyWithSelect = withSelect((select, blockData) => {
    const parentClientId = select('core/block-editor').getBlockRootClientId(
        selectedClientId
    );

    return {
        innerBlocks: select('core/block-editor').getBlocks(blockData.clientId),
    };
});

所以在这里,我将innerBlocks作为该页面上的块数组,看起来像这样(第一个元素):

0:
attributes: {title: "Enter Title", review: "Enter review", rating: "Add Rating", reviewerName: "Enter Name", reviewDate: "Enter Date", …}
clientId: "2413142124"
innerBlocks: []
isValid: true
name: "something/some-item"
originalContent: "<div>something</div>"

我有没有办法在我的编辑功能中使用这个innerBlocks变量,并以某种方式呈现该块?不使用<InnerBlocks >的原因是我必须一个一个地渲染它们,因此每个块在我的滑块中都是一个单独的元素。我需要这样的东西:

const reviews = this.props.innerBlocks;

return (
   <div>
       <div className="carousel">
           <Slider {...slickSettings} className={classnames(this.props.className)}>
               { reviews.map((block, i) => {
                    return (
                        block.render() // this line is the issue, doesn't have to be render, but
                                       // any other way of rendering block separately from InnerBlocks
                         )

                 })
               }
           </Slider>
       </div>
   </div>
)
wordpress wordpress-gutenberg
1个回答
0
投票

一段时间以来,我一直在努力获得类似的东西。我需要的只是返回一个带有renderToString的渲染块的字符串,但是我认为您可以轻松地删除该字符串并返回块本身。

[深入研究WordPress's repo之后,我认为答案必须与函数getSaveElement( nameOfBlock, attributesObject, [optionalInnerBlocks] )相关联

我的代码看起来像这样:


import { registerBlockType, getSaveElement } from '@wordpress/blocks';
import { renderToString } from '@wordpress/element';

const arrayOfInnerBlocks = something.innerBlocks; //for example purposes
const getRenderedEl = ( attributes ) => {
    const el = renderToString(
        getSaveElement( 'core/cover', attributes ) //this is the main thing!
    );
    return el;
}

// i'm deconstructing the innerBlock item and just getting attributes.
const blockElements = arrayOfInnerBlocks.map( {attributes} => ({ individualBlock: getRenderedEl(attributes) }) )


所以对您来说,这样的事情:

const reviews = this.props.innerBlocks;
const getRenderedEl = ( {attributes, name} ) => getSaveElement( name, attributes ); //this is the main
return (
   <div>
       <div className="carousel">
           <Slider {...slickSettings} className={classnames(this.props.className)}>
               { reviews.map( getRenderedEl ) }
           </Slider>
       </div>
   </div>
)

希望这就是您想要的!

© www.soinside.com 2019 - 2024. All rights reserved.