块编辑器开发文档

RichText 参考

💡 云策文档标注

概述

RichText 是一个组件,允许开发者渲染一个可编辑的输入框,为用户提供格式化块内容(如加粗、斜体、链接等)的功能。它专为块编辑器设计,提供一致样式、占位文本和控制格式化选项等内置功能。

关键要点

  • RichText 组件用于在块编辑器中创建可格式化的文本输入,支持加粗、斜体、链接等操作。
  • 它提供一致的前端和管理端样式,允许设置块级元素(如 div、h2、p)作为容器。
  • 开发者可以控制允许的格式化选项,例如通过 allowedFormats 属性限制为仅加粗或斜体。
  • 核心块如 Button、Heading、Quote 和 Search 都使用 RichText 组件,可作为最佳实践参考。
  • 常见问题包括 HTML 标签显示错误、不需要的格式化选项出现,可通过调整 save 函数或使用属性解决。

代码示例

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" // 这里的标签是输出元素,在管理端可编辑
                value={ attributes.content } // 任何现有内容,来自数据库或属性默认值
                allowedFormats={ [ 'core/bold', 'core/italic' ] } // 允许内容加粗或斜体,但不允许其他格式化选项
                onChange={ ( content ) => setAttributes( { content } ) } // 将更新后的内容存储为块属性
                placeholder={ __( 'Heading...' ) } // 在用户添加内容前显示此文本
            />
        );
    },

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

        return <RichText.Content { ...blockProps } tagName="h2" value={ attributes.content } />; // 将 <h2>编辑器添加的内容...</h2> 保存到数据库以供前端显示
    }
} );

注意事项

  • 如果 HTML 格式化标签(如 )在前端被转义显示,检查 save 函数是否正确使用 RichText.Content。
  • 如果不需要任何格式化,考虑使用基本 input 或 textarea 元素替代 RichText。
  • 使用 withoutInteractiveFormatting 属性可消除所有格式化选项,或使用 allowedFormats 限制允许的格式。
  • 要禁用特定格式类型(如内联图像),可使用 wp.richText.unregisterFormatType 函数,并确保在插件或主题中正确加载脚本。

📄 原文内容

RichText is a component that allows developers to render a contenteditable input, providing users with the option to format block content to make it bold, italics, linked, or use other formatting.

The RichText component is extremely powerful because it provides built-in functionality you won’t find in other components:

  • Consistent Styling in the Admin and Frontend: The editable container can be set to any block-level element, such as a div, h2 or p tag. This allows the styles you apply in style.css to more easily apply on the frontend and admin, without having to rewrite them in editor.css.
  • Cohesive Placeholder Text: Before the user writes their content, it’s easy to include placeholder text that’s already styled to match the rest of the block editor.
  • Control Over Formatting Options: It’s possible to dictate exactly which formatting options you want to allow for the RichText field. For example, you can dictate whether to allow the user to make text bold, italics or both.

Unlike other components that exist in the Component Reference section, RichText lives separately because it only makes sense within the block editor, and not within other areas of WordPress.

Property reference

For a list of the possible properties to pass your RichText component, check out the component documentation on GitHub.

Core blocks using the RichText component

There are a number of core blocks using the RichText component. The JavaScript edit function linked below for each block can be used as a best practice reference while creating your own blocks.

  • Button: RichText is used to enter the button’s text.
  • Heading: RichText is used to enter the heading’s text.
  • Quote: RichText is used in two places, for both the quotation and citation text.
  • Search: RichText is used in two places, for both the label above the search field and the submit button text.

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
    }
} );

Common issues and solutions

While using the RichText component a number of common issues tend to appear.

HTML formatting tags display in the content

If the HTML tags from text formatting such as <strong> or <em> are being escaped and displayed on the frontend of the site, this is likely due to an issue in your save function. Make sure your code looks something like <RichText.Content tagName="h2" value={ heading } /> (JSX) within your save function instead of simply outputting the value with <h2>{ heading }</h2>.

Unwanted formatting options still display

Before moving forward, consider if using the RichText component makes sense at all. Would it be better to use a basic input or textarea element? If you don’t think any formatting should be possible, these HTML tags may make more sense.

If you’d still like to use RichText, you can eliminate all of the formatting options by specifying the withoutInteractiveFormatting property.

If you want to limit the formats allowed, you can specify using allowedFormats property in your code, see the example above or the component documentation for details.

Disable specific format types in Editor

The RichText component uses formats to display inline elements, for example images within the paragraph block. If you just want to disable a format from the editor, you can use the unregisterFormatType function. For example to disable inline images, use:

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

To apply, you would need to enqueue the above script in your plugin or theme. See the JavaScript tutorial for how to load JavaScript in WordPress.