首页 > 解决方案 > 从块数组中渲染块 - 古腾堡

问题描述

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

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

标签: wordpresswordpress-gutenberg

解决方案


您使用BlockEditorProvider在编辑函数中显示块,使用 map 函数列出所有数组并在其中显示值属性中的元素。如果需要,您可以检测onChangeonInput的变化。

<BlockEditorProvider
    value={ block[ index ] }
    onInput={ ( state ) => {
        console.log( state );
    } }
    onChange={ ( state ) => {
        const newBlockContent = block.concat( [] );
        newBlockContent[ index ] = state;
        setAttributes( {
            myBlocks: newBlockContent,
        } );
    } }
>
    <SlotFillProvider>
        <BlockTools>
            <WritingFlow>
                <ObserveTyping>
                    <BlockList />
                </ObserveTyping>
            </WritingFlow>
        </BlockTools>
        <Popover.Slot />
    </SlotFillProvider>
</BlockEditorProvider>;

推荐阅读