WordPress 5.7 中新的区块变体API

新属性 isActive

块变体设置现在可以包含一个新属性 isActive。此可选属性是一个功能,古腾堡编辑器使用该功能来确定给定块的变化形式。这意味着诸如的块编辑器界面,比如BlockCard可以显示块变体的标题和描述,而不是块的标题和描述。

我们需要此功能由块/插件作者显式实现,因为在许多情况下,通过动态检查所有块属性来尝试找到匹配项是没有意义的。一个例子是 embed 我们可能已经更改了响应属性块,因此找不到匹配项。

单个块变体中的示例:

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

所有变体都使用相同的匹配函数时的示例:

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

用法示例:

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