reactjs - 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 不需要在前面定义,它是在添加内容时。
有没有人有同样的想法并可以帮助存档?
谢谢。
解决方案
我建议将图像存储在数组属性中。然后您可以使用该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 }
/>
}) }
推荐阅读
- sql - LEFT 外连接返回返回重复的行,即使添加了不同的
- twig - 转储(项目)在 Twig 模板 drupal 中不起作用
- python - 将csv转换为熊猫
- javascript - 如何为此javascript代码创建自动循环?
- c++ - 无法使用静态库在 linux 远程项目上重建:错误 MS8012,Visual Studio 2019
- javascript - javascript fetch函数获取语法错误
- azure-service-fabric - Service Fabric 更改应用程序计数,而无需重新部署整个程序包
- matlab - 如何修复 mex 文件中的非法字符错误
- swift - 这可以在控制器中定期执行测试吗?
- excel - 数据源开始和结束范围变量