可以使用块属性和useEffect()
在您的edit
功能:
useEffect(() => {
// If the ID is already set, we don\'t need to do anything
if (attributes.id) {
return;
}
// The ID attribute isn\'t set, so we\'ll create it and set it now
setAttributes({
id: 123, // This is just for example purposes, you can set up your ID however you want
});
}, []); // Empty array ensures this effect only runs once
One thing to note: 如果使用现有ID属性复制/粘贴/复制现有块,则不会再次运行ID创建代码。
如果您正在寻找一种更健壮的解决方案来为块生成唯一ID(并且可以更改ID),那么我使用了类似的技术(see code here) 对于我的一个块,它将post ID和实例ID结合起来创建唯一ID。如果重新排列块,插入新块,等等。它会根据需要重新生成ID。