wp-interactivity-api
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseWP Interactivity API
WordPress Interactivity API
When to use
使用场景
Use this skill when the user mentions:
- Interactivity API, ,
@wordpress/interactivity - ,
data-wp-interactive,data-wp-on--*,data-wp-bind--*,data-wp-context - block / module-based view scripts,
viewScriptModule - hydration issues or “directives don’t fire”.
当用户提及以下内容时,可使用本技能:
- Interactivity API、,
@wordpress/interactivity - 、
data-wp-interactive、data-wp-on--*、data-wp-bind--*,data-wp-context - 区块/ 基于模块的视图脚本,
viewScriptModule - hydration问题或“指令未触发”问题。
Inputs required
所需输入
- Repo root + triage output ().
wp-project-triage - Which block/theme/plugin surfaces are affected (frontend, editor, both).
- Any constraints: WP version, whether modules are supported in the build.
- 代码库根目录 + 分类输出()。
wp-project-triage - 受影响的区块/主题/插件范围(前端、编辑器、或两者均受影响)。
- 任何限制条件:WordPress版本、构建是否支持模块。
Procedure
操作步骤
1) Detect existing usage + integration style
1) 检测现有使用方式与集成风格
Search for:
data-wp-interactive@wordpress/interactivityviewScriptModule
Decide:
- Is this a block providing interactivity via view script module?
block.json - Is this theme-level interactivity?
- Is this plugin-side “enhance existing markup” usage?
If you’re creating a new interactive block (not just debugging), prefer the official scaffold template:
- (via
@wordpress/create-block-interactive-template)@wordpress/create-block
搜索以下内容:
data-wp-interactive@wordpress/interactivityviewScriptModule
判断:
- 是否为通过视图脚本模块提供交互性的区块?
block.json - 是否为主题级别的交互性?
- 是否为插件端“增强现有标记”的使用场景?
如果您要创建新的交互式区块(而非仅调试),建议使用官方脚手架模板:
- (通过
@wordpress/create-block-interactive-template使用)@wordpress/create-block
2) Identify the store(s)
2) 识别存储(Store)
Locate store definitions and confirm:
- state shape,
- actions (mutations),
- callbacks/event handlers used by .
data-wp-on--*
定位存储定义并确认:
- 状态结构,
- 动作(变更),
- 所使用的回调/事件处理器。
data-wp-on--*
3) Server-side rendering (best practice)
3) 服务器端渲染(最佳实践)
Pre-render HTML on the server before outputting to ensure:
- Correct initial state in the HTML before JavaScript loads (no layout shift).
- SEO benefits and faster perceived load time.
- Seamless hydration when the client-side JavaScript takes over.
在输出前在服务器端预渲染HTML,以确保:
- JavaScript加载前,HTML中包含正确的初始状态(无布局偏移)。
- 利于SEO,且感知加载速度更快。
- 客户端JavaScript接管时实现无缝hydration。
Enable server directive processing
启用服务器端指令处理
For components using , add :
block.jsonsupports.interactivityjson
{
"supports": {
"interactivity": true
}
}For themes/plugins without , use to process directives.
block.jsonwp_interactivity_process_directives()对于使用的组件,添加:
block.jsonsupports.interactivityjson
{
"supports": {
"interactivity": true
}
}对于未使用的主题/插件,使用处理指令。
block.jsonwp_interactivity_process_directives()Initialize state/context in PHP
在PHP中初始化状态/上下文
Use to define initial global state:
wp_interactivity_state()php
wp_interactivity_state( 'myPlugin', array(
'items' => array( 'Apple', 'Banana', 'Cherry' ),
'hasItems' => true,
));For local context, use :
wp_interactivity_data_wp_context()php
<?php
$context = array( 'isOpen' => false );
?>
<div <?php echo wp_interactivity_data_wp_context( $context ); ?>>
...
</div>使用定义初始全局状态:
wp_interactivity_state()php
wp_interactivity_state( 'myPlugin', array(
'items' => array( 'Apple', 'Banana', 'Cherry' ),
'hasItems' => true,
));对于本地上下文,使用:
wp_interactivity_data_wp_context()php
<?php
$context = array( 'isOpen' => false );
?>
<div <?php echo wp_interactivity_data_wp_context( $context ); ?>>
...
</div>Define derived state in PHP
在PHP中定义派生状态
When derived state affects initial HTML rendering, replicate the logic in PHP:
php
wp_interactivity_state( 'myPlugin', array(
'items' => array( 'Apple', 'Banana' ),
'hasItems' => function() {
$state = wp_interactivity_state();
return count( $state['items'] ) > 0;
}
));This ensures directives like render correctly on first load.
data-wp-bind--hidden="!state.hasItems"For detailed examples and patterns, see .
references/server-side-rendering.md当派生状态影响初始HTML渲染时,在PHP中复现该逻辑:
php
wp_interactivity_state( 'myPlugin', array(
'items' => array( 'Apple', 'Banana' ),
'hasItems' => function() {
$state = wp_interactivity_state();
return count( $state['items'] ) > 0;
}
));这可确保等指令在首次加载时正确渲染。
data-wp-bind--hidden="!state.hasItems"有关详细示例和模式,请参阅。
references/server-side-rendering.md4) Implement or change directives safely
4) 安全实现或修改指令
When touching markup directives:
- keep directive usage minimal and scoped,
- prefer stable data attributes that map clearly to store state,
- ensure server-rendered markup + client hydration align.
WordPress 6.9 changes:
- is deprecated and will be removed in future versions. It broke context inheritance and caused issues with client-side navigation. Avoid using it.
data-wp-ignore - Unique directive IDs: Multiple directives of the same type can now exist on one element using the separator (e.g.,
---anddata-wp-on--click---plugin-a="...").data-wp-on--click---plugin-b="..." - New TypeScript types: and
AsyncAction<ReturnType>help with async action typing.TypeYield<T>
For quick directive reminders, see .
references/directives-quickref.md处理标记指令时:
- 尽量减少指令使用范围,保持作用域清晰,
- 优先使用与存储状态清晰映射的稳定数据属性,
- 确保服务器端渲染的标记与客户端hydration保持一致。
WordPress 6.9 变更:
- 已被弃用,将在未来版本中移除。它会破坏上下文继承并导致客户端导航问题,请避免使用。
data-wp-ignore - 唯一指令ID:现在可使用分隔符在单个元素上添加多个同类型指令(例如
---和data-wp-on--click---plugin-a="...")。data-wp-on--click---plugin-b="..." - 新增TypeScript类型:和
AsyncAction<ReturnType>可帮助实现异步动作的类型定义。TypeYield<T>
如需快速查阅指令,请参阅。
references/directives-quickref.md5) Build/tooling alignment
5) 构建/工具对齐
Verify the repo supports the required module build path:
- if it uses , prefer its conventions.
@wordpress/scripts - if it uses custom bundling, confirm module output is supported.
验证代码库是否支持所需的模块构建路径:
- 如果使用,请遵循其约定。
@wordpress/scripts - 如果使用自定义打包工具,请确认支持模块输出。
6) Debug common failure modes
6) 调试常见故障模式
If “nothing happens” on interaction:
- confirm the is enqueued/loaded,
viewScriptModule - confirm the DOM element has ,
data-wp-interactive - confirm the store namespace matches the directive’s value,
- confirm there are no JS errors before hydration.
See .
references/debugging.md如果交互时“无任何反应”:
- 确认已入队/加载,
viewScriptModule - 确认DOM元素包含属性,
data-wp-interactive - 确认存储命名空间与指令值匹配,
- 确认hydration前无JavaScript错误。
请参阅。
references/debugging.mdVerification
验证
- indicates
wp-project-triageafter your change (if applicable).signals.usesInteractivityApi: true - Manual smoke test: directive triggers and state updates as expected.
- If tests exist: add/extend Playwright E2E around the interaction path.
- 若相关,修改后应显示
wp-project-triage。signals.usesInteractivityApi: true - 手动冒烟测试:指令触发且状态按预期更新。
- 若已有测试:围绕交互路径添加/扩展Playwright端到端测试。
Failure modes / debugging
故障模式/调试
- Directives present but inert:
- view script not loading, wrong module entrypoint, or missing .
data-wp-interactive
- view script not loading, wrong module entrypoint, or missing
- Hydration mismatch / flicker:
- server markup differs from client expectations; simplify or align initial state.
- derived state not defined in PHP: use with closures.
wp_interactivity_state()
- Initial content missing or wrong:
- not set in
supports.interactivity(for blocks).block.json - not called (for themes/plugins).
wp_interactivity_process_directives() - state/context not initialized in PHP before render.
- Layout shift on load:
- derived state like missing on server, causing
state.hasItemsattribute to be absent.hidden
- derived state like
- Performance regressions:
- overly broad interactive roots; scope interactivity to smaller subtrees.
- Client-side navigation issues (WordPress 6.9):
- and
getServerState()now reset between page transitions—ensure your code doesn't assume stale values persist.getServerContext() - Router regions now support for rendering overlays (modals, pop-ups) dynamically.
attachTo
- 指令存在但无响应:
- 视图脚本未加载、模块入口错误或缺少。
data-wp-interactive
- 视图脚本未加载、模块入口错误或缺少
- Hydration不匹配/闪烁:
- 服务器端标记与客户端预期不符;简化或对齐初始状态。
- 派生状态未在PHP中定义:使用带闭包的。
wp_interactivity_state()
- 初始内容缺失或错误:
- 区块的中未设置
block.json。supports.interactivity - 主题/插件未调用。
wp_interactivity_process_directives() - 渲染前未在PHP中初始化状态/上下文。
- 区块的
- 加载时布局偏移:
- 服务器端缺少等派生状态,导致
state.hasItems属性缺失。hidden
- 服务器端缺少
- 性能退化:
- 交互根范围过广;将交互性限定在更小的子树中。
- 客户端导航问题(WordPress 6.9):
- 和
getServerState()现在会在页面切换时重置——确保代码不依赖过期的持久化值。getServerContext() - 路由区域现在支持来动态渲染覆盖层(模态框、弹窗)。
attachTo
Escalation
升级处理
- If repo build constraints are unclear, ask: "Is this using or a custom bundler (webpack/vite)?"
@wordpress/scripts - Consult:
references/server-side-rendering.mdreferences/directives-quickref.mdreferences/debugging.md
- 若代码库构建限制不明确,可询问:“是否使用或自定义打包工具(webpack/vite)?”
@wordpress/scripts - 参考:
references/server-side-rendering.mdreferences/directives-quickref.mdreferences/debugging.md