如何使用clsx正确合并Tailwind CSS类名解决默认样式被覆盖问题
问题原因
JSX 中后定义的属性会覆盖先定义的同名属性,你的代码里先写了合并后的className,再展开包含className的props,props自带的className直接覆盖了前面合并好的类名,所以只有未传入className时默认类才会生效。
修复方案
方案1:调整属性顺序
把{...props}放到自定义className之前,避免合并后的类被覆盖:
const Button = ({ children, ...props }): JSX.Element => { return ( <ADButton {...props} className={clsx('rounded-none', props.className)} > {children} </ADButton> ); };
方案2(更推荐):单独提取className
解构props时把className单独拎出来,剩余props不带className属性,从根源避免覆盖问题,逻辑更清晰:
const Button = ({ children, className: customClassName, ...restProps }): JSX.Element => { return ( <ADButton className={clsx('rounded-none', customClassName)} {...restProps} > {children} </ADButton> ); };
两种方案都可以实现预期效果:传入className时自动合并为rounded-none pt-0,未传入时仅保留rounded-none。
内容的提问来源于stack exchange,提问作者frre tyy
相关产品推荐
相关产品推荐

