从一系列块中渲染块-古腾堡

时间:2019-11-29 16:16:50

标签: wordpress wordpress-gutenberg

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

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

1 个答案:

答案 0 :(得分: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>
)

希望这就是您想要的!