我为插件制作了一个Gutenberg块,但是它不再按预期工作。它与古腾堡(Gutenberg)的第一个版本一起使用,从那时起我不知道发生了什么变化。
我阅读了一些类似的问题,但没有有用的答案: -Wordpress Gutenberg block -Gutenberg Block validation failed -Gutenberg Block Validation Failed ( not expecting children )
我的详细问题:
当我将块添加到内容中时,它看起来很完美,而且如果我保存帖子,我也会按预期看到小部件。
问题是当我编辑现有文章时,该块被打破了: https://ibb.co/6vHRcXC
代码看起来不错,我可以在代码编辑器中看到它:https://ibb.co/tDMGnPY
更新文章,小部件仍可在前端使用。
控制台会显示此警告,并显示以下错误:https://ibb.co/Gk80skq
似乎在生成的代码中缺少属性data-id ,但我不明白为什么。
我尝试更改此属性名称(如果[data-id]是保留字,则为 ),但没有任何更改。
我尝试更改此属性的值(我需要将其设置为整数,但尝试添加大写,小写和下划线前缀),但没有任何更改。
一点上下文:对于使用古腾堡创建的每个块,我都需要一个唯一的ID ,在整个站点中都没有重复的,我需要将此ID带到前端的JavaScript函数中 >。请告诉我我在做什么错,是否还有另一种方法可以做到这一点。
这是我的Gutenberg块的完整JavaScript源:
(function () {
let iconSvg = wp.element.createElement('svg', {width: 20, height: 20},
wp.element.createElement('path', {d: "M10,0C4.478,0,0,4.478,0,10c0,5.521,4.478,10,10,10c5.521,0,10-4.479,10-10C20,4.478,15.521,0,10,0zM5.039,9.226c-0.786,0-1.425,0.765-1.425,1.705H2.576c0-1.512,1.104-2.742,2.462-2.742s2.463,1.23,2.463,2.742H6.463C6.463,9.991,5.825,9.226,5.039,9.226z M10,18.049c-3.417,0-6.188-2.41-6.188-5.382h12.375C16.188,15.639,13.418,18.049,10,18.049zM16.387,10.931c0-0.94-0.639-1.705-1.426-1.705c-0.785,0-1.424,0.765-1.424,1.705h-1.039c0-1.512,1.105-2.742,2.463-2.742s2.463,1.23,2.463,2.742H16.387z"})
);
wp.blocks.registerBlockType('plugin-name/gutenberg-block', {
title: 'CustomBlockName',
icon: iconSvg,
category: 'widgets',
edit: (props) => {
// @TODO: we need a unique ID for each block!
this.myId = props.attributes.itemId || Math.floor(Math.random() * 8388607); /// Medium int max value is 8388607;
props.setAttributes(
{
itemId: myId
}
);
return wp.element.createElement(
'div',
{},
[
wp.element.createElement(
'div',
{},
[
wp.element.createElement(
'img',
{
src: PluginNameGutenbergBlock.preview_image
}
)
]
)
]
);
},
save: (props) => {
let dataId = props.attributes.itemId;
return wp.element.createElement(
'div',
{},
[
wp.element.createElement(
'div',
{
class: 'plugin-name-outer'
},
[
wp.element.createElement(
'div',
{
'class': 'plugin-name-container-async gutenberg-block',
'data-id': dataId,
'data-type': PluginNameGutenbergBlock.item_type
},
wp.element.createElement(
'div',
{
'class': 'plugin-name-' + PluginNameGutenbergBlock.use_template
}, {},
[
wp.element.createElement(
'img',
{
src: PluginNameGutenbergBlock.loader_url
}
)
]
)
)
]
)
]
);
}
});
}());
答案 0 :(得分:0)
我了解自己的错误,因此我发布了此答案,希望对其他人有所帮助。
当我创建一个新块时,我首先为属性data-id
生成一个随机值:
/// Inside edit function
this.myId = props.attributes.itemId || Math.floor(Math.random() * 8388607); /// Medium int max value is 8388607;
然后,我在共享的props
对象中设置此值:
/// Inside edit function
props.setAttributes(
{
itemId: myId
}
);
然后,当我保存刚创建的脚本的块时,找到生成的值:
/// Inside save function
let dataId = props.attributes.itemId;
因此,块创建工作良好,但是当我打开现有帖子时,我的脚本无法找到保存的值,因此dataId
函数内的save
的值为{{1} }和属性undefined
丢失。 这是保存的块和生成的块之间的区别。
缺少的部分是data-id
块,该块从保存的代码中读取值并使它们在attributes
和edit
函数中可用。
这是我的解决方案:
save