首页 > 解决方案 > Gutenberg Block -> 媒体上传 - 不同图像的数组

问题描述

有人可以帮我为属性内的图像创建数组吗?

此刻我做了:

attributes: {
    Bg_URL: { type: 'string' },
    Bg_ID: { type: 'number' },
    Bg_ALT: { type: 'string'},
    icon_1_URL: { type: 'string' },
    icon_1_ID: { type: 'number' },
    icon_1_ALT: { type: 'string'},
    icon_2_URL: { type: 'string' },
    icon_2_ID: { type: 'number' },
    icon_2_ALT: { type: 'string'},
    icon_3_URL: { type: 'string' },
    icon_3_ID: { type: 'number' },
    icon_3_ALT: { type: 'string'},
},

然后更新函数:

const onSelectImage = (name) => (e) => {
        setAttributes({
            [name+'_URL']: e.url,
            [name+'_ID']: e.id,
            [name+'_ALT']: e.alt,
        });
    };

和媒体上传:

<MediaUpload
    onSelect={onSelectImage('Bg')}
    type="image"
    value={attributes.Bg_ID}
    render={({open}) => (
        <figure className={!attributes.Bg_ID ? ' image-button' : ' image-preview'} onClick={open} >
            {!attributes.Bg_ID ? __("Upload Image") : <img src={attributes.Bg_URL} />}
        </figure>
    )}
/>

好吧,我做了一个函数来更新属性中的特定图像,但我想在那里有图像数组,它将存储所有块图像,并且从 onSelect 我可以传递该图像的名称/ID/键来存储,这我会打电话给

images.key.url

理想情况下,我会看到 RichText 相同,我不需要单独定义每个内容,但会有一个数组“内容”,还有这样的东西吗?

value={ attributes.content.heading }
onChange={ ( content.heading ) => setAttributes( { content.heading } ) }

其中 .heading 不需要在前面定义,它是在添加内容时。

有没有人有同样的想法并可以帮助存档?

谢谢。

标签: reactjswordpresswordpress-gutenberggutenberg-blocks

解决方案


我建议将图像存储在数组属性中。然后您可以使用该MediaUpload组件来创建和编辑“图库”。

onSelectMeida功能:

const onSelectMedia = (media) => {
    setAttributes({
        images: [{
            id: media.id,
            url: media.url,
            alt: media.alt,
        }],
    });
};

MediaUpload组件:

<MediaUploadCheck>
    <MediaUpload
        multiple={ true }
        gallery={ true }
        onSelect={ (media) => onSelectMedia(media) }
        allowedTypes={ ['image'] }
        accept="image/*"
        value={ images.map(item => item.id) }
        render={ ({open}) => {
            return (
                <Fragment>
                    <Button
                        isPrimary={ true }
                        onClick={ (event) => {
                            event.stopPropagation();
                            open();
                        } }
                    >
                        { images.length > 0 ? __('Edit Images', 'pb') : __('Select Images', 'pb') }
                    </Button>
                </Fragment>
            );
        } }
    />
</MediaUploadCheck>

然后你可以使用 a 渲染图像map

{ images.length > 0 && images.map(image => {
    <img    
        key={ image.id }
        src={ image.url }
        alt={ image.alt }
    />
}) }

推荐阅读