WordPress 5.7区块变体API新特性isActive详解

全新功能发布:块变体激活状态属性isActive

古腾堡编辑器现已支持为块变体设置新增可选属性isActive。这一创新功能将帮助编辑器智能识别特定块变体的激活状态,从而在块编辑器界面(如BlockCard组件)中精准展示变体的标题与描述,而非默认的块级信息。值得注意的是,该功能需要由块或插件开发者主动实现,因为盲目通过动态检测所有块属性来匹配变体往往缺乏实际意义。例如,对于embed类型块,若响应式属性发生变更,传统匹配方式可能失效。

单个变体激活状态配置示例

“`javascript
const variations = [
{
name: ‘wordpress’,
title: ‘WordPress’,
keywords: [‘post’, ‘blog’],
description: __(‘Embed a WordPress post.’),
attributes: {
providerNameSlug: ‘wordpress’
},
isActive: (blockAttributes, variationAttributes) =>
blockAttributes.providerNameSlug === variationAttributes.providerNameSlug
}
];
“`

统一匹配函数实现示例

“`javascript
const variations = [
{
name: ‘twitter’,
title: ‘Twitter’,
icon: embedTwitterIcon,
keywords: [‘tweet’, ‘social’],
description: __(‘Embed a tweet.’),
patterns: [/^https?:\/\/(www.)?twitter.com\/.+/i],
attributes: {
providerNameSlug: ‘twitter’,
responsive: true
}
},
{
name: ‘wordpress’,
title: ‘WordPress’,
icon: embedWordPressIcon,
keywords: [‘post’, ‘blog’],
description: __(‘Embed a WordPress post.’),
attributes: {
providerNameSlug: ‘wordpress’
}
}
];

variations.forEach(variation => {
if (variation.isActive) return;
variation.isActive = (blockAttributes, variationAttributes) =>
blockAttributes.providerNameSlug === variationAttributes.providerNameSlug;
});

export default variations;
“`

全新钩子函数useBlockDisplayInformation

新增钩子函数useBlockDisplayInformation为开发者提供获取块显示信息的强大工具。该函数会智能考虑每个块变体的isActive属性,并返回匹配变体的title、icon和description信息。当找不到匹配的块变体时,系统会回退至块类型的默认信息;若块类型本身不存在,则返回null值。

实际应用示例

“`javascript
import { useBlockDisplayInformation, BlockIcon } from ‘@wordpress/block-editor’;

function myBlockInformation(clientId) {
const blockInformation = useBlockDisplayInformation(clientId);
if (!blockInformation) return null;

const { title, icon, description } = blockInformation;
return (

{title}

{description}

);
}
“`

文章网址:https://www.wpbull.com/news/1900.html