如何在WordPress中使用简单的自定义gutenberg块获得唯一的id



我正在为每个自定义gutenberg块获取一个唯一的id。我发现useInstanceId。这可以和这个语法一起使用吗?

registerBlockType('custom/block', {
title: 'Custom',

edit() {
return (<p>{unqiue-block-id}</p>)
},
save() {
return (<p>{unqiue-block-id}</p>)
},
});

您可以使用props中的clientId来解决此问题。不幸的是,它只是生活在编辑功能的道具中。因此,您需要将clientId作为一个额外的属性来传递。我自己也很难用useInstanceId来完成这项工作,因为如果我理解正确的话,你需要用HigherComponent来完成它。所以我选择了clientId解决方案。

我从这里得到了最初的想法

以下是使用clientId完成代码时的样子。

registerBlockType('custom/block', {
title: 'Custom',
attributes: {
yourId: {
type: 'string',
}
},
edit: props => {
const {
attributes: {
yourId,
},
clientId,
setAttributes,
} = props;
setAttributes({ yourId: clientId });
return (
<p>{yourId}</p>
);
},
save: props => {
const {
attributes: {
yourId,
},
} = props;
return (
<p>{yourId}</p>
);
},
});

最新更新