【问题标题】:How to get a unique id with a simple custom gutenberg block in WordPress?如何在 WordPress 中使用简单的自定义古腾堡块获取唯一 ID?
【发布时间】:2021-04-11 09:55:08
【问题描述】:

我正在尝试为每个自定义古腾堡块获取唯一的 ID。我找到了useInstanceId。可以使用这种语法吗?

registerBlockType('custom/block', {
    title: 'Custom',
    
    edit() {
        return (<p>{unqiue-block-id}</p>)
    },
    save() {
        return (<p>{unqiue-block-id}</p>)
    },
});

【问题讨论】:

    标签: php wordpress wordpress-theming wordpress-gutenberg gutenberg-blocks


    【解决方案1】:

    您可以使用props 中的clientId 解决此问题。不幸的是,它只存在于编辑功能的道具中。因此,您需要将 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>
            );
        },
    });
    

    【讨论】:

    • 完美!正是我想要的:) 谢谢!效果很好
    • Lars,我也是,但现在我将使用此解决方案,稍后再查看useInstanceId 主题。据我所知,您必须使用更高阶的组件,但这是一个完全不同的主题。如果您能找到一个好的解决方案和示例,请告诉我们;)
    • 另外,如果您希望在任何地方使用 clientID 作为 CSS 选择器,请确保在其前面加上一个字母,因为有时 clientId 以数字开头,这不是有效的 CSS 类名.喜欢let safeCssClientIdClass = 'a' + clientId
    猜你喜欢
    • 1970-01-01
    • 2023-02-11
    • 1970-01-01
    • 2022-06-11
    • 2022-10-22
    • 2022-12-16
    • 2021-03-27
    • 2019-09-25
    • 2022-10-20
    相关资源
    最近更新 更多