跳转到主要内容

RichText 参考

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

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

  • 管理界面与前端样式一致: 可编辑容器可以设置为任何块级元素,如 div、h2 或 p 标签。这使得您在 style.css 中应用的样式能更轻松地同时应用于前端和管理界面,无需在 editor.css 中重写。
  • 统一的占位符文本: 在用户输入内容前,可以轻松添加已预先设置好样式的占位符文本,以匹配区块编辑器的整体风格。
  • 对格式化选项的控制: 您可以精确指定允许在 RichText 字段中使用哪些格式化选项。例如,可以决定是否允许用户将文本设置为加粗、斜体或两者兼用。

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

属性参考

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

使用 RichText 组件的核心区块

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

  • 按钮: RichText 用于输入按钮文本。
  • 标题: RichText 用于输入标题文本。
  • 引用: RichText 用于两个地方,分别用于引文和出处文本。
  • 搜索: RichText 用于两个地方,分别用于搜索字段上方的标签和提交按钮文本。

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 组件是否完全合理。使用基本的 input 或 textarea 元素是否更好?如果您认为不应允许任何格式,这些 HTML 标签可能更合适。

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

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

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

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

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

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