微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在 WordPress 中使用简单的自定义古腾堡块获取唯一 ID?

如何解决如何在 WordPress 中使用简单的自定义古腾堡块获取唯一 ID?

我正在尝试为每个自定义古腾堡块获取唯一 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>
        );
    },});

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。