Gutenberg 区块编辑器文档

title: "RichText 参考" post_status: publish comment_status: open taxonomy: category: - gutenberg-docs post_tag: - Reference Guides - Repos - Data


RichText 参考

RichText 是一个允许开发者渲染 contenteditable 输入框的组件,为用户提供格式化块级内容的选项,例如加粗、斜体、添加链接或其他格式。

RichText 组件功能极其强大,因为它提供了其他组件不具备的内置功能:

组件参考部分中的其他组件不同,RichText 单独存在,因为它仅在区块编辑器中有意义,而不适用于 WordPress 的其他区域。

属性参考

如需了解可传递给 RichText 组件的属性列表,请查看 GitHub 上的组件文档

使用 RichText 组件的核心区块

有许多核心区块使用了 RichText 组件。下面为每个区块链接的 JavaScript 编辑函数,可作为创建自定义区块时的最佳实践参考。

Example

import { registerBlockType } from '@wordpress/blocks';
import { useBlockProps, RichText } from '@wordpress/block-editor';

registerBlockType( /* ... */, {
    // ...

    attributes: {
        content: {
            type: 'string',
            source: 'html',
            selector: 'h2',
        },
    },

    edit( { attributes, setAttributes } ) {
        const blockProps = useBlockProps();

        return (
            <RichText
                { ...blockProps }
                tagName="h2" // The tag here is the element output and editable in the admin
                value={ attributes.content } // Any existing content, either from the database or an attribute default
                allowedFormats={ [ 'core/bold', 'core/italic' ] } // Allow the content to be made bold or italic, but do not allow other formatting options
                onChange={ ( content ) => setAttributes( { content } ) } // Store updated content as a block attribute
                placeholder={ __( 'Heading...' ) } // Display this text before any content has been added by the user
            />
        );
    },

    save( { attributes } ) {
        const blockProps = useBlockProps.save();

        return <RichText.Content { ...blockProps } tagName="h2" value={ attributes.content } />; // Saves <h2>Content added in the editor...</h2> to the database for frontend display
    }
} );

常见问题与解决方案

使用 RichText 组件时,常会出现一些典型问题。

HTML 格式标签在内容中显示

如果文本格式化所用的 HTML 标签(如 <strong><em>)被转义并在网站前端显示,这很可能是保存函数的问题。请确保在保存函数中使用类似 <RichText.Content tagName="h2" value={ heading } />(JSX)的代码,而不是简单地用 <h2>{ heading }</h2> 输出值。

不需要的格式选项仍然显示

在继续之前,请考虑使用 RichText 组件是否完全合理。使用基本的 inputtextarea 元素是否更好?如果您认为不应允许任何格式,这些 HTML 标签可能更合适。

如果您仍想使用 RichText,可以通过指定 withoutInteractiveFormatting 属性来消除所有格式选项。

如果您想限制允许的格式,可以在代码中指定 allowedFormats 属性,详情请参见上面的示例或组件文档

在编辑器中禁用特定格式类型

RichText 组件使用格式来显示内联元素,例如段落块内的图像。如果您只想在编辑器中禁用某种格式,可以使用 unregisterFormatType 函数。例如,要禁用内联图像,请使用:

wp.richText.unregisterFormatType( 'core/image' );

要应用此更改,您需要在插件或主题中排队加载上述脚本。有关如何在 WordPress 中加载 JavaScript,请参阅 JavaScript 教程:如何在 WordPress 中加载 JavaScript