首页 > 解决方案 > 有没有办法在父块中知道您正在编辑该父块的内部块?

问题描述

props.isSelected仅当您在父块内而不是在该块的内部块内进行编辑时,父块的 才为真。

如何从父块检查用户是否正在编辑该父块的内部块(无论多深)

我问是因为我想为父级的 innerBlocks 做某种切换功能,直到您选择父级块并尝试使用时才可见,props.isSelected但显然当您开始编辑内部块时,它会立即消失,因为父级不再被选中

这是一个简单的代码,应该演示我在说什么

registerBlockType('test/parent', {
    name: 'Parent',
    edit: (props) => {
      const template = [['test/child'],['test/child']];
      if (props.isSelected) {
        return <InnerBlocks template={template}/>;
      }
      return <div>Click me to see my inner block</div>;
    },
    save: (props) => {
        return <InnerBlocks.Content />;
    }
};
registerBlockType('test/child', {
    name: 'Child',
    parent: ['test/parent'],
    edit: (props) => {
      return <div>I'm the child I can have some more nested blocks but if you click on me I will be gone because my parent won't want me anymore, I wish somebody could edit me :(</div><InnerBlocks />;
    },
    save: (props) => {
        return <div>I'm the child</div><InnerBlocks.content />;
    }
}

标签: reactjswordpress-gutenberg

解决方案


经过大量研究后,我创建了自己的函数来确定是否选择了内部块(需要 wp-data)

这是代码

registerBlockType('test/parent', {
    name: 'Parent',
    edit: (props) => {
        const template = [['test/child'],['test/child']];
        if (props.isSelected || hasSelectedInnerBlock(props)) {
            return <InnerBlocks template={template}/>;
        }
        return <div>Click me to see my inner block</div>;
    },
    save: (props) => {
        return <InnerBlocks.Content />;
    }
};

function hasSelectedInnerBlock(props) {
    const select = wp.data.select('core/editor');
    const selected = select.getBlockSelectionStart();
    const inner = select.getBlock(props.clientId).innerBlocks;
    for (let i = 0; i < inner.length; i++) {
        if (inner[i].clientId === selected || inner[i].innerBlocks.length && hasSelectedInnerBlock(inner[i])) {
            return true;
        }
    }
    return false;
};

推荐阅读