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

如何为Gutenberg扩展块追加自定义类名而非覆盖默认类?

解决WordPress Gutenberg块追加自定义类名不覆盖默认类的问题

嘿,这个问题我之前折腾Gutenberg扩展的时候也碰到过!你现在的代码是直接替换了className,所以默认类就被覆盖了,只需要稍微调整一下,把原来的类名和自定义类合并起来就好啦。

修改后的代码应该是这样的:

const withClass = createHigherOrderComponent( ( BlockListBlock ) => {
    return ( props ) => {
        // 先获取原有的wrapperProps,避免直接覆盖
        const { wrapperProps = {} } = props;
        // 合并原有类名和自定义类名
        const updatedClassName = wrapperProps.className 
            ? `${wrapperProps.className} my-custom-class` 
            : 'my-custom-class';
        // 更新wrapperProps
        const updatedWrapperProps = {
            ...wrapperProps,
            className: updatedClassName
        };
        return <BlockListBlock { ...props } wrapperProps={ updatedWrapperProps } />;
    };
}, 'withClass' );

代码说明:

  • 首先用解构获取原有的wrapperProps,如果它不存在的话就默认用空对象,避免报错
  • 处理className的时候,先检查原有的类名是否存在:如果存在,就用模板字符串把原有类名和自定义类名拼在一起(注意加空格分隔);如果不存在,就直接用自定义类名
  • 最后把更新后的wrapperProps传给BlockListBlock,这样就既能保留块的默认类,又能追加你的自定义类啦

这样修改之后,你的自定义类my-custom-class就会和块原本的默认类一起出现在容器上,不会再覆盖默认样式了~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 07:07:39