gutenberg-docs/docs/reference-guides/interactivity-api
2026-03-27 01:08:43 +08:00
..
core-concepts docs: add 183 translated files 2026-03-27 01:08:43 +08:00
directives-and-store.md docs: add 183 translated files 2026-03-27 01:08:43 +08:00
iapi-about.md docs: add 183 translated files 2026-03-27 01:08:43 +08:00
iapi-faq.md docs: add 183 translated files 2026-03-27 01:08:43 +08:00
iapi-quick-start-guide.md docs: add 183 translated files 2026-03-27 01:08:43 +08:00
README.md docs: add 183 translated files 2026-03-27 01:08:43 +08:00

title post_status comment_status taxonomy
交互性 API 参考 publish open
category post_tag
gutenberg-docs
Interactivity Api
Reference Guides
Repos

交互性 API 参考

交互性 API 于 WordPress 6.5 中引入,为开发者提供了一种标准方式,用于向区块前端添加交互功能。该 API 也用于许多核心 WordPress 区块,包括搜索、查询、导航和文件。

这一标准让开发者更容易创建丰富的交互式用户体验,从简单的计数器或弹窗,到更复杂的功能,如即时页面导航、即时搜索、购物车或结账。

区块之间可以共享数据、操作和回调。这使得区块间的通信更简单且不易出错。例如,点击“加入购物车”区块可以无缝更新单独的“购物车”区块。

要了解更多关于交互性 API 起源的信息,请查阅原始提案。你也可以查看合并公告状态更新文章和官方的 Trac 工单

交互性 API 由 @wordpress/interactivity 包提供支持,该包自 v6.5 起已捆绑在 WordPress 核心中。

导航交互性 API 文档

使用以下链接定位您感兴趣的主题。如果您之前从未使用过交互性 API请考虑按顺序阅读以下资源。

要更深入地了解交互性 API 是什么,或找到您可能对此标准有疑问的答案,请查看以下资源:

  • 关于交互性 API: 了解更多关于 API 目标以及为何使用标准为区块添加交互性的原因。
  • 常见问题解答: 查找关于其背后技术及替代方案的一些常见问题的解答。

交互性 API 的要求

交互性 API 已包含在 WordPress 6.5 的核心中。对于更低版本,您需要在 WordPress 安装中安装并激活 Gutenberg 17.5 或更高版本。

同样重要的是要强调,区块创建的工作流程没有改变,所有先决条件保持不变。这些包括:

一旦您设置了区块开发环境并运行 WordPress 6.5+(或 Gutenberg 17.5+),就可以开始创建交互了。

代码要求

为项目添加 interactivity

通过以下命令将 Interactivity API 安装到你的项目中:

npm install @wordpress/interactivity --save

将 store 导入到你的 view.js 中。更多信息请参阅 store 文档

import { store } from '@wordpress/interactivity';

block.json 添加 interactivity 支持

若要表明区块支持 Interactivity API 功能,请在区块的 block.json 文件的 supports 属性中添加 "interactivity": true

// block.json
"supports": {
    "interactivity": true
},

请参阅 interactivity 支持属性文档 以获取此属性的更详细说明。

使用 viewScriptModule 加载交互性 API JavaScript 代码

交互性 API 提供了 @wordpress/interactivity 脚本模块。使用交互性 API 的 JavaScript 应作为脚本模块实现,以便它们可以依赖 @wordpress/interactivity脚本模块自 WordPress 6.5 起可用。区块可以使用 viewScriptModule 区块元数据 轻松地将其脚本模块加入队列:

// block.json
{
   ...
   "viewScriptModule": "file:./view.js"
}

使用 viewScriptModule 还需要为 wp-scriptsbuildstart 脚本添加 --experimental-modules 标志,以确保脚本模块的正确构建。

// package.json
{
    "scripts": {
        ...
		"build": "wp-scripts build --experimental-modules",
		"start": "wp-scripts start --experimental-modules"
	}

Add wp-interactive directive to a DOM element

To "activate" the Interactivity API in a DOM element (and its children), add the wp-interactive directive to the DOM element in the block's render.php or save.js files.

<div data-wp-interactive="myPlugin">
	<!-- Interactivity API zone -->
</div>

Refer to the wp-interactive documentation for a more detailed description of this directive.

文档与示例

这里有一些额外的资源,供您进一步了解/阅读交互性 API

已开设一个跟踪议题,以便协调与交互性 API 文档相关的工作:交互性 API 文档 - 跟踪议题 #53296