所以我在Wordpress Gutenberg中使用嵌套块。我在应用引导容器类的元素上应用包装器。显然,我只想在最外面的块上使用它,而不是在嵌套块内的块上。
有没有办法知道当前块是否在InnerBlocks 父块的定义?我当前正在blocks.getSaveElement 滤器
有没有更好的方法?
上下文:在以前的古腾堡版本中,曾经有布局属性来实现这一点,但后来它被删除了。我使用的是3.9.0版。
这是我的包装函数的缩写版本:
    namespace.saveElement = ( element, blockType, attributes ) => {
        const hasBootstrapWrapper = hasBlockSupport( blockType.name, \'bootstrapWrapper\' );
        if (hasBlockSupport( blockType.name, \'anchor\' )) {
            element.props.id = attributes.anchor;
        }
        if (hasBootstrapWrapper) {
            // HERE I NEED TO CHECK IF THE CURRENT ELEMENT IS INSIDE A INNERBLOCKS ELEMENT AND THEN APPLY DIFFERENT WRAPPER
            var setWrapperInnerClass = wrapperInnerClass;
            var setWrapperClass = wrapperClass;
            if (attributes.containerSize) {
                setWrapperInnerClass = wrapperInnerClass + \' \' + attributes.containerSize;
            }
            if (attributes.wrapperType) {
                setWrapperClass = wrapperClass + \' \' + attributes.wrapperType;
            }
            const setWrapperAnchor = (attributes.wrapperAnchor) ? attributes.wrapperAnchor : false;
            return (
                newEl(\'div\', { key: wrapperClass, className: setWrapperClass, id: setWrapperAnchor},
                    newEl(\'div\', { key: wrapperInnerClass, className: setWrapperInnerClass},
                        element
                    )
                )
            );
        } else {
            return element;
        }
    };
wp.hooks.addFilter(\'blocks.getSaveElement\', \'namespace/gutenberg\', namespace.saveElement);
 
                SO网友:Abubakar Wazih Tushar
                getBlockParents 将准确工作。您可以使用getBlockParents 使用clientId 该街区的,getBlockParents 如果当前块位于任何块下,将返回所有父块id。如果当前块不在任何块下,则返回空白
以下是您可以使用的方法:
const innerBlock = "namespace/block-name";
const parentBlocks = wp.data.select( \'core/block-editor\' ).getBlockParents(props.clientId); 
const parentAttributes = wp.data.select(\'core/block-editor\').getBlocksByClientId(parentBlocks);
var is_under_inner = false;
for (i = 0; i < parentAttributes.length; i++) {
    if ( parentAttributes[i].name == innerBlock ) {
        is_under_inner = true;
    }
}
//console.log(is_under_inner);