首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >获取Wordpress Gutenberg块属性,以便在前端使用

获取Wordpress Gutenberg块属性,以便在前端使用
EN

WordPress Development用户
提问于 2021-03-05 19:50:53
回答 1查看 1.3K关注 0票数 1

在生成Carousel的Gutenberg块中,我从块的uniqueId设置clientId属性,并将其保存到保存函数的标记中,作为Html。

我这样做是为了我可以有一个独特的身份,例如,我呈现给前面的每一个旋转木马。

问题是,我需要在前端js代码中传递这个唯一的id,例如,我正在生成的每个旋转木马的不同选项。但是,我如何在js代码中获得这个惟一的id,它将仅用于前端?

EN

回答 1

WordPress Development用户

回答已采纳

发布于 2021-08-19 07:52:46

在Gutenberg中为块获取唯一标识的一种方法是使用clientId,但方式不同。如果只使用clientId字符串一次,则可以将其存储在块的属性中,这些属性将存储在数据库中,并且可以在任何给定的时间检索它,诀窍是在第一次加载块时存储块给您的clientId,然后在页面重新加载时停止WordPress编辑该属性。这样,每次重新加载页面时,都会有不同的clientId,但是第一个clientId保存的属性在属性中仍然可用。代码应该如下所示:

代码语言:javascript
复制
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>
    );
}

此外,在属性支柱中,您必须这样做:

代码语言:javascript
复制
    "attributes": {
        "id": {
            "type": "string",
            "default": ""
        }

        //...The rest of your attributes
    }

我测试了这种方法,它对我正在构建的插件非常有效。

我还读过这个问题,它说您可以使用withInstanceId获得唯一的标识符,但我还没有测试过这种方法。

票数 3
EN
页面原文内容由WordPress Development提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://wordpress.stackexchange.com/questions/384579

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档