我正在创建一个自定义 Gutenberg 块。它在保存时工作正常并出现在前端,但我一回到它就会读取。
阻止包含无效或意外内容
当我去解决这个块时,我在我的组件figure
周围插入了一个额外的东西。MediaUpload
控制台输出显示块的结构,除了添加的文本。
我看到了一个类似的问题,即编辑功能的 HTML 节点与保存功能 HTML 节点不匹配。看到之后,我加倍检查以确保我的节点排成一行,并且我相信它们确实如此,除非我跳过了某些内容。这是块的代码:
const { RichText, MediaUpload, PlainText } = wp.editor;
const { registerBlockType } = wp.blocks;
const { Button } = wp.components;
import './style.scss';
import './editor.scss';
registerBlockType('stackoverflow/image-card', {
title: "Image Card",
icon: 'feedback',
category: 'common',
attributes: {
title: {
source: 'text',
selector: '.imageCard__title'
},
body: {
type: 'string',
source: 'children',
selector: '.imageCard__body'
},
imageAlt: {
attribute: 'alt',
selector: '.imageCard__image'
},
imageUrl: {
attribute: 'src',
selector: '.imageCard__image'
}
},
edit({ attributes, className, setAttributes }) {
const getImageButton = (openEvent) => {
if(attributes.imageUrl) {
return (
<img
src={ attributes.imageUrl }
onClick={ openEvent }
className="image"
/>
);
}
else {
return (
<div className="button-container">
<Button
onClick={ openEvent }
className="button button-large"
>
Pick an image
</Button>
</div>
);
}
};
return (
<div className="container">
<MediaUpload
onSelect={ media => { setAttributes({ imageAlt: media.alt, imageUrl: media.url }); } }
type="image"
value={ attributes.imageID }
render={ ({ open }) => getImageButton(open) }
/>
<h3>
<PlainText
onChange={ content => setAttributes({ title: content }) }
value={ attributes.title }
placeholder="Your card title"
className="heading"
/>
</h3>
<div className={className}>
<RichText
onChange={ content => setAttributes({ body: content }) }
value={ attributes.body }
multiline="p"
placeholder="Your card text"
/>
</div>
</div>
);
},
save({ attributes }) {
const cardImage = (src, alt) => {
if(!src) return null;
if(alt) {
return (
<img
className="card__image"
src={ src }
alt={ alt }
/>
);
}
// No alt set, so let's hide it from screen readers
return (
<img
className="card__image"
src={ src }
alt=""
aria-hidden="true"
/>
);
};
return (
<div className="container">
<img
className="card__image"
src={ attributes.imageUrl }
alt={ attributes.imageAlt }
/>
<h3 className="card__title">{ attributes.title }</h3>
<div className="card__body">
{ attributes.body }
</div>
</div>
);
}
});