React中拼接多个className时如何去除类名间的多余空格
问题根源
模板字符串拼接类名时,如果c({ active: !image })返回空字符串,或anotherclassName为全空格字符串,拼接后的字符串中间就会出现连续多余空格,trim()仅能处理首尾空格,无法处理中间的连续空格。
解决方案
方法1:数组过滤拼接(推荐)
将所有待拼接的类名放入数组,过滤掉空值/全空格值后再用空格拼接,逻辑清晰且扩展性强,后续新增类名直接往数组中添加即可,还支持按条件动态插入类名:
const baseClass = "someclass" const c = prefix(baseClass); const classList = [ baseClass, c({ active: !image }), anotherclassName // 过滤假值+全空格字符串,也可以直接用.filter(Boolean)仅过滤空字符串/undefined等假值 ].filter(item => typeof item === 'string' ? item.trim() !== '' : Boolean(item)) <div className={classList.join(' ')}> <p>Brooklyn</p> </div>
方法2:正则替换连续空格
如果不想改动原有拼接逻辑,可以在trim()后新增正则替换,把所有连续的多个空格替换为单个空格:
const baseClass = "someclass" const c = prefix(baseClass); <div className={`${baseClass} ${c({ active: !image })} ${anotherclassName}`.trim().replace(/\s+/g, ' ')}> <p>Brooklyn</p> </div>
内容的提问来源于stack exchange,提问作者Harshitha
相关产品推荐
相关产品推荐

