如何为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
相关产品推荐
相关产品推荐

