我正在尝试创建一个自定义的WordPress gutenberg块,该块允许我选择任何图像和文本。
我可以使用此代码创建块,并且可以在网站的前端看到内容,但是如果查看该块进行编辑,则该块会崩溃。
控制台显示以下错误:-
块验证:cgb/block-imagecta
的块验证失败(
对象{名称:“ cgb / block-imagecta”,图标:{…},属性:{…},关键字:(3)[…],保存:save(),标题:“ imagecta-CGB Block”,类别: “ common”,编辑:edit()
}
)。
由save
函数生成的内容:
<div class="wp-block-cgb-block-imagecta"><div class="imageCtaBg"><img class="bg" alt="sergserge"/><p></p></div></div>
从帖子正文中检索到的内容:
<div class="wp-block-cgb-block-imagecta"><div class="imageCtaBg"><img class="bg" alt="sergserge"/><p>dxfbxdfbxdfbfb</p></div></div>
这完全与属性有关吗?
/**
* BLOCK: imagecta
*
* Registering a basic block with Gutenberg.
* Simple block, renders and saves the same content without any interactivity.
*/
// Import CSS.
import './editor.scss';
import './style.scss';
const {__} = wp.i18n; // Import __() from wp.i18n
const {registerBlockType} = wp.blocks; // Import registerBlockType() from wp.blocks
const {FormFileUpload} = wp.components;
const {RichText, MediaUpload} = wp.blockEditor;
registerBlockType('cgb/block-imagecta', {
title: __('imagecta - CGB Block'),
icon: 'shield',
category: 'common',
keywords: [
__('imagecta — CGB Block'),
__('CGB Example'),
__('create-guten-block'),
],
attributes: {
content: {
type: 'html',
selector: '.captionText',
},
logo: {
type: 'string',
default: null,
},
},
edit: (props) => {
const {attributes: {content}, setAttributes} = props;
function onImageSelect(imageObject) {
setAttributes({
logo: imageObject.sizes.full.url
});
}
const onChangeContent = (newContent) => {
setAttributes({content: newContent});
};
// Creates a <p class='wp-block-cgb-block-imagecta'></p>.
return (
<div className={props.className}>
<MediaUpload
onSelect={onImageSelect}
type="image"
value={logo} // make sure you destructured backgroundImage from props.attributes!
render={({open}) => (
<button onClick={open}>
Upload Image!
</button>
)}
/>
<div className='imageCtaBg'>
<img src={logo} class="bg" alt={'sergserge'}/>
<RichText
tagName={'p'}
className='captionText'
onChange={onChangeContent}
value={content}
placeholder='Enter text...'
/>
</div>
</div>
);
},
save: (props) => {
const {attributes: {content}, setAttributes} = props;
return (
<div className={props.className}>
<div className={'imageCtaBg'}>
<img src={props.attributes.logo} className="bg" alt={'sergserge'}/>
<RichText.Content tagName={"p"} value={props.attributes.content}/>
</div>
</div>
);
},
});
答案 0 :(得分:1)
问题在于content属性。
我没有给Richtext提供'captionText'类,而是对其进行了包装div,并将content属性更改为以下内容:-
content: {
type: 'string',
source:'html',
selector: '.captionText',
},
这会在该div中找到文本,并允许我更新该块而没有任何验证问题。