You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

editor.BlockListBlock过滤器异常:SCRIPT_DEBUG状态影响返回对象

解决Gutenberg editor.BlockListBlock钩子在SCRIPT_DEBUG关闭时返回WithSelect的问题

嘿,我之前也踩过Gutenberg这个坑!生产环境(SCRIPT_DEBUG关闭)下,Gutenberg会用高阶组件(比如WithSelect)包裹原始的BlockListBlock组件做性能优化,这就导致我们直接拿到的不是预期的基础组件实例。下面是问题复现和解决方案:

问题现象

  • 开启调试模式(在wp-config.php中设置define( 'SCRIPT_DEBUG', true );)时,editor.BlockListBlock钩子能返回正确的BlockListBlock组件,代码正常运行
  • 关闭调试模式(SCRIPT_DEBUG未定义或设为false)时,钩子返回的是WithSelect组件,直接使用会出现异常

问题代码

const { createHigherOrderComponent } = wp.compose;
const withClientIdClassName = createHigherOrderComponent( ( BlockListBlock ) => {
    // BlockListBlock returns as "WithSelect" with debug off
    // and returns as the correct component with debug on
    console.log(BlockListBlock);
    return ( props ) => {
        const {attributes, name} = props;
        if(name === 'project/block-name'){
            return <BlockListBlock { ...props } className={'classes-i-want-on-this'} />;
        } else {
            return <BlockListBlock { ...props } />;
        }
    };
}, 'withClientIdClassName' );
wp.hooks.addFilter( 'editor.BlockListBlock', 'classNames-for-cells', withClientIdClassName );

解决方案

我们不需要纠结BlockListBlock被多少高阶组件包裹,只需要聚焦于修改props中的类名即可。用Gutenberg内置的工具函数安全合并类名,能适配两种模式的组件结构:

const { createHigherOrderComponent } = wp.compose;
const { classnames } = wp.utils; // 引入Gutenberg的类名合并工具

const withClientIdClassName = createHigherOrderComponent( ( BlockListBlock ) => {
    return ( props ) => {
        // 解构props,分离出类名和其他属性
        const { className, name, ...restProps } = props;
        
        // 给指定区块添加自定义类名,同时保留原有类名
        let updatedClassName = className;
        if(name === 'project/block-name'){
            updatedClassName = classnames(className, 'classes-i-want-on-this');
        }

        // 把更新后的props传递给BlockListBlock组件
        return <BlockListBlock { ...restProps } className={ updatedClassName } />;
    };
}, 'withClientIdClassName' );

wp.hooks.addFilter( 'editor.BlockListBlock', 'classNames-for-cells', withClientIdClassName );

关键说明

  1. 使用classnames工具函数可以安全合并类名,避免覆盖原有样式类或者出现空类名的问题
  2. 先解构props修改类名,再传递给组件的方式,不管组件是原始实例还是被高阶组件包裹,都能稳定运行
  3. 不需要判断组件类型,只专注于props的修改,符合Gutenberg的组件设计逻辑

注:该项目通过create-guten-block初始化,这个方案在调试和生产模式下都能正常工作。

内容的提问来源于stack exchange,提问作者Brayn_7

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 09:27:51