问题描述
我正在尝试为每个自定义古腾堡块获取唯一 ID。我找到了 useInstanceId。可以使用这种语法吗?
registerBlockType('custom/block',{
title: 'Custom',edit() {
return (<p>{unqiue-block-id}</p>)
},save() {
return (<p>{unqiue-block-id}</p>)
},});
解决方法
您可以使用 clientId
中的 props
解决此问题。不幸的是,它只是存在于编辑功能的道具中。因此,您需要将 clientId 作为额外属性提供。
我自己在用 useInstanceId
完成这个过程中挣扎得太厉害了,因为如果我理解正确的话,你需要用一个 HigherComponent 来完成它。所以我选择了 clientId
解决方案。
我最初的想法来自here
以下是使用 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>
);
},});