古腾堡。如何仅为特定的支柱类型注册自定义图块样式

时间:2021-05-11 作者:uruk

对于core/paragraph-块,我想注册一个自定义样式。这很好用

const { registerBlockStyle } = wp.blocks;
wp.domReady( () => {
    registerBlockStyle( \'core/paragraph\', {
        name: \'lead\',
        label: \'Lead\'
    } );
} );
现在,我希望此自定义样式仅适用于某些帖子类型,例如仅适用于帖子类型;过帐;。因此,我必须在编辑器中访问当前的帖子类型。但这不起作用:

const { registerBlockStyle } = wp.blocks;
const { useSelect } = wp.data;

wp.domReady( () => {
    // This is not working:
    const postType = useSelect( select => select( \'core/editor\').getCurrentPostType() );

    if ( postType === \'post\' ) {

        registerBlockStyle( \'core/paragraph\', {
            name: \'lead\',
            label: \'Lead\'
        } );
    }
} );
我得到的只是控制台中的React minify错误:

Invalid hook call. Hooks can only be called inside of the body of a function component.
我想我必须把所有的东西都打包成一个组件或什么的。

How can I make this working?

可选选项

我可以生成一个单独的javascript文件,该文件仅在当前帖子类型为;过帐;。

1 个回复
最合适的回答,由SO网友:Sally CJ 整理而成

我怎样才能让它工作?

不确定是否有更好的方法,但我会用subscribe()@wordpress/data 包装:

const { registerBlockStyle } = wp.blocks;
const { subscribe, select } = wp.data;

wp.domReady( () => {
    const unsubscribe = subscribe( () => {
        const postType = select( \'core/editor\' ).getCurrentPostType();

        // 1. Unsubscribe once we\'ve got the post type.
        if ( postType ) {
            unsubscribe();
            console.log( `Post type: ${ postType }. Unsubscribed.` );

            // 2. Register the block style if the post type is \'post\'.
            if ( \'post\' === postType ) {
                registerBlockStyle( \'core/paragraph\', {
                        name: \'lead\',
                        label: \'Lead\'
                } );
            }
        }
    } );
} );

相关推荐