我正在尝试将bootstrap5 carousel组件实现为Gutenberg块。它似乎都在按预期工作,除了添加;“活动”;类设置为第一个元素。
我试图通过使用getBlockParents
和getBlocksByClientId
以下是JS代码:
const select = window.wp.data.select(\'core/block-editor\');
blocks.registerBlockType(\'natural/bootstrap5-carousel-item\', {
apiVersion: 2,
title: __(\'Carousel Item\'),
icon: \'format-gallery\',
category: \'design\',
parent: [\'natural/bootstrap5-carousel\'],
example: {},
edit: function () {
return el(
\'div\',
useBlockProps({
style: {
padding: \'20px\',
border: \'2px solid #000\'
}
}),
el( InnerBlocks )
)
},
save: function (props) {
const parentBlocks = select.getBlockParents(props.clientId); // empty in save method, works in console
const directParent = select.getBlocksByClientId(parentBlocks[parentBlocks.length - 1])[0];
const siblings = directParent.innerBlocks;
let classNameSuffix = \'\';
if (siblings[0].attributes.clientId === props.clientId) {
classNameSuffix = \' active\';
}
return el(
\'div\',
useBlockProps.save({
className: \'carousel-item\' + classNameSuffix
}),
el( InnerBlocks.Content )
)
},
});
不幸的是,我尝试的方法返回了一个错误,因为parentBlocks为空。知道为什么吗?该代码在web控制台中工作,但在save方法中似乎正在中断。