我创建了以下古腾堡块:
const { __ } = wp.i18n;
const { registerBlockType, Heading } = wp.blocks;
const { Fragment } = wp.element;
const { RichText, InnerBlocks } = wp.editor;
function hall_block_gray_content() {
registerBlockType( 'hallmark/gray-content-container', {
title: __( 'Gray Content Container' ),
icon: 'grid-view',
category: 'hallmark-blocks',
keywords: [
__( 'Hallmark gray content' ),
__( 'Hallmark' ),
__( 'Gray content container' ),
],
attributes:{
contentHeading: {
type: 'string',
source: 'children',
selector: 'h4',
default: ''
},
textContent: {
type: 'string'
}
},
edit: function( props ) {
var textContent = props.attributes.textContent;
var contentHeading = props.attributes.contentHeading;
function onChangeTextContent( content ) {
props.setAttributes( { textContent: content } );
}
function onChangeHeading (heading) {
props.setAttributes( { contentHeading: heading} );
}
return (
<div className={ props.className }>
<label className="editor-content-section-label">Content for gray section</label>
<RichText
tagName="h4"
value={contentHeading}
onChange={onChangeHeading}
placeholder={ __( 'Add a heading' ) }
keepPlaceholderOnFocus
/>
<RichText
tagName="p"
className={props.className}
onChange={onChangeTextContent}
value={textContent}
placeholder={ __( 'Add content' ) }
keepPlaceholderOnFocus
/>
</div>
);
},
save: function( props ) {
return(
<div className={props.className}>
<div className="gray-bg">
<div className="constrain content">
{ props.attributes.contentHeading ? <RichText.Content tagName="h4" value={ props.attributes.contentHeading } /> : "" }
<RichText.Content tagName="p" value={ props.attributes.textContent } />
</div>
</div>
</div>
);
},
} );
/* Gray content block ends */
}
export default hall_block_gray_content();
我希望标题部分是可选的,即,如果有人不输入标题,则<h4></h4>
不应呈现。我使用三元运算符检查props.attributes.contentHeading
函数中是否存在save
,并尝试有条件地呈现<h4>
标签。
但是它总是像这样渲染一个空的<h4>
容器标签:
<h4></h4><p>Content is here</p>
正确的方法是什么?