首页 > 解决方案 > 古腾堡向编辑器添加富文本按钮,按钮不出现

问题描述

我在这里学习教程 - https://wordpress.org/gutenberg/handbook/designers-developers/developers/tutorials/format-api/

第 1 步 - 注册一个新格式,这工作正常,我可以在控制台中看到我的新格式类型

第 2 步 - 我已将代码添加到 my-custom-format.js 以使按钮出现,并按照说明将相应的 wp-element 和 wp-editor 包添加到 PHP 文件中的依赖项数组中。

.php 文件

<?php
/**
 * Plugin Name: My custom format
 */

function my_custom_format_script_register() {
    wp_register_script(
        'my-custom-format-js',
        plugins_url( 'my-custom-format.js', __FILE__ ),
        array( 'wp-element', 'wp-editor', 'wp-rich-text',  )
    );
}
add_action( 'init', 'my_custom_format_script_register' );

function my_custom_format_enqueue_assets_editor() {
    wp_enqueue_script( 'my-custom-format-js' );
}
add_action( 'enqueue_block_editor_assets', 'my_custom_format_enqueue_assets_editor' );

JS文件

( function( wp ) {
    wp.richText.registerFormatType(
        'my-custom-format/sample-output', {
            title: 'Sample output',
            tagName: 'samp',
            className: null,
        }
    );
    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: 'samp',
            className: null,
            edit: MyCustomButton,
        }
    );
} )( window.wp );

我是否需要安装 @wordpress/rich-text 模块才能使其正常工作?

标签: wordpressapitextwysiwygwordpress-gutenberg

解决方案


推荐阅读