reactjs - 有没有办法在父块中知道您正在编辑该父块的内部块?
问题描述
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 />;
}
}
解决方案
经过大量研究后,我创建了自己的函数来确定是否选择了内部块(需要 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;
};
推荐阅读
- oracle - Oracle中的分页与动态查询
- ios - 如何将结构值加载到 collectionView 单元格中
- powershell - 使用文件链接的 XPath 从 Web 下载具有动态名称的文件
- ansible - Ansible:如何为角色实现条件?(得到错误)
- node.js - 如何在 nodejs/electron 应用程序中触发带有附件的“新电子邮件”窗口
- java - 使用 try/catch 将数字存储到用户定义的数组中并在最后一个数组索引中继续
- python - 使用排除迭代计算列表项的乘积
- php - 更新 src 内容时自动刷新页面
- jekyll - 如何使用{{a variable [inside] a variable}}?
- python - python中的knuth shuffle