Gutenberg具有多个类的注册器FormatType

时间:2019-05-29 作者:Lyle Bennett

我正在使用我创建的插件向Gutenbergs RichTextToolbar添加一个按钮,但我不知道如何将多个类添加到我创建的标记/span中。

( function( wp ) {
    var MyCustomButton = function( props ) {
        return wp.element.createElement(
            wp.editor.RichTextToolbarButton, {
                icon: \'editor-code\',
                title: \'Sample output\',
                onClick: function() {
                    props.onChange( wp.richText.toggleFormat(
                        props.value,
                        { type: \'my-custom-format/sample-output\' }
                    ) );
                },
                isActive: props.isActive,
            }
        );
    }
    wp.richText.registerFormatType(
        \'my-custom-format/sample-output\', {
            title: \'Sample output\',
            tagName: \'span\',
            className: \'classname another-classname\',  //this line needs the help - works as just \'classname\' no spaces but can only wrap with one class then
            edit: MyCustomButton,
        }
    );
} )( window.wp );
控制台错误显示:

类名必须以字母开头,后跟任意数量的连字符、字母或数字。

因此,空间正在创建错误,但如何向该函数添加2个类?我也尝试了以下不起作用的方法。

className: {\'has-primary-color has-text-color\'},

2 个回复
SO网友:Evgeniy Z.

从registerFormatType函数可以看出source code, 类名中只允许使用字母、数字、“\\”和“-”。

if ( ! /^[_a-zA-Z]+[a-zA-Z0-9-]*$/.test( settings.className ) ) {
    window.console.error(
        \'A class name must begin with a letter, followed by any number of 
         hyphens, letters, or numbers.\'
    );
    return;
}
因此,不能用空格分隔两个类名。

SO网友:Simon

您可以在toggleFormat的选项部分添加额外的类。registerFormatType中指定的类名用于区分不同的格式,因此需要是一个类。

在您的示例中:

( function( wp ) {
    var MyCustomButton = function( props ) {
        return wp.element.createElement(
            wp.editor.RichTextToolbarButton, {
                icon: \'editor-code\',
                title: \'Sample output\',
                onClick: function() {
                    props.onChange( wp.richText.toggleFormat(
                        props.value,
                        {
                            type: \'my-custom-format/sample-output\',
                            attributes: {
                                class: \'another-classname\'
                            }
                        }
                    ) );
                },
                isActive: props.isActive,
            }
        );
    }
    wp.richText.registerFormatType(
        \'my-custom-format/sample-output\', {
            title: \'Sample output\',
            tagName: \'span\',
            className: \'classname\', 
            edit: MyCustomButton,
        }
    );
} )( window.wp );

相关推荐