获取古腾堡中块的唯一id的一种方法是使用clientId,但方式不同。如果clientId字符串只使用一次,则可以将其存储在块的属性中,该属性将存储在数据库中,并且可以在任何给定的时间检索它,诀窍是在块首次装载时存储块提供给您的clientId,然后在页面重新加载时停止WordPress编辑该属性。这样,每次重新加载页面时,您都会有一个不同的clientId,但使用第一个clientId保存的属性仍将在属性中可用。代码应如下所示:
import { useEffect } from \'@wordpress/element\';
import { useBlockProps } from \'@wordpress/block-editor\';
// ... Whatever else you want to import
export default function Edit({ clientId, attributes, setAttributes }) {
const blockProps = useBlockProps();
/*useEffect is a React hook that triggers during the component\'s life
cycle parts, but when giving it an empty array as a second argument
it will only trigger on mounting the component*/
useEffect(() => {
//This conditional is useful to only set the id attribute once
//when the component mounts for the first time
attributes.id === \'\'
&& setAttributes( { "id": clientId } )
}, [])
//... the rest of your logic goes here
return (
<div { ...blockProps }>
{// You can use attributes.id as a class or id or whatever serves your purpose }
<div className={attributes.id}>
//...more JSX or HTML
</div>
</div>
);
}
此外,在属性属性属性中,必须执行以下操作:
"attributes": {
"id": {
"type": "string",
"default": ""
}
//...The rest of your attributes
}
我测试了这种方法,它对我正在构建的插件非常有效。
我也读过this question 也就是说你可以使用withInstanceId
获取唯一标识符,但我尚未测试该方法。