我不确定这是否可能以直接的方式实现。
您可以添加一个属性来检查块是否具有内部块。然后在中使用它save
是否呈现包装器。它可以工作,但不是一种非常干净的解决方案:
const { __ } = wp.i18n;
const { registerBlockType } = wp.blocks;
const { InnerBlocks } = wp.blockEditor;
const { useSelect } = wp.data;
const { useEffect } = wp.element;
registerBlockType("my-plugin/my-block", {
title: __("My block"),
icon: "carrot",
category: "common",
attributes: {
innerBlocks_length: {
type: "number",
default: 0
}
},
edit: props => {
const { className, clientId, setAttributes } = props;
const { innerBlocks_length } = useSelect(select => ({
innerBlocks_length: select("core/block-editor").getBlockCount(clientId)
}));
useEffect(() => {
setAttributes({ innerBlocks_length });
}, [innerBlocks_length]);
return (
<div className={className}>
<div className="innerBlocks_wrapper">
<InnerBlocks />
</div>
</div>
);
},
save: props => {
const { innerBlocks_length } = props.attributes;
return (
<div>
{innerBlocks_length > 0 && (
<div className="innerBlocks_wrapper">
<InnerBlocks.Content />
</div>
)}
</div>
);
}
});