在生成Carousel的Gutenberg块中,我从块的uniqueId设置clientId属性,并将其保存到保存函数的标记中,作为Html。
我这样做是为了我可以有一个独特的身份,例如,我呈现给前面的每一个旋转木马。
问题是,我需要在前端js代码中传递这个唯一的id,例如,我正在生成的每个旋转木马的不同选项。但是,我如何在js代码中获得这个惟一的id,它将仅用于前端?
发布于 2021-08-19 07:52:46
在Gutenberg中为块获取唯一标识的一种方法是使用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
}我测试了这种方法,它对我正在构建的插件非常有效。
我还读过这个问题,它说您可以使用withInstanceId获得唯一的标识符,但我还没有测试过这种方法。
https://wordpress.stackexchange.com/questions/384579
复制相似问题