首页 > 解决方案 > 在 Wordpress 古腾堡编辑器的根容器中添加一个类

问题描述

Wordpress gutenberg 编辑器有一个内容的根容器,用“is-root-container”类标识。我想在预览更改时(在移动设备、平板电脑、桌面设备之间)向该容器添加类,以便我可以设置编辑器内容的样式以模拟相应的响应式 CSS。

我还没有找到一种方法来做到这一点,所以我有一个解决方法来使用 editor.BlockListBlock 过滤器将类添加到每个块的包装器中。但是,这并不是特别有效,尤其是在有大量块的情况下。

这是我目前正在使用的,但它会为每个块运行,效率不高。

import htm from 'https://unpkg.com/htm?module'
const html = htm.bind(wp.element.createElement);

const { createHigherOrderComponent } = wp.compose;
const { useSelect } = wp.data;
const { addFilter } = wp.hooks;

const withPreviewDeviceClassname = createHigherOrderComponent(
    ( BlockListBlock ) => {
        return ( props ) => {
            const previewMode = useSelect( (select) => select('core/edit-post').__experimentalGetPreviewDeviceType() );
            const className = 'tw ' + (previewMode == 'Tablet' ? 'tablet' : (previewMode == 'Desktop' ? 'desktop tablet' : '') );

            return (
                html`<${BlockListBlock}
                    ...${props}
                    className=${className}
                />`
            );
        };
    },
    'withPreviewDeviceClassname'
);

addFilter(
    'editor.BlockListBlock',
    'cms/blocklist-plugin',
    withPreviewDeviceClassname
);

标签: wordpresswordpress-gutenbergwp-editor

解决方案


推荐阅读