React+Tailwind+TypeScript条件设置className报错求助
解决React+Tailwind+TypeScript按钮className条件赋值错误
你遇到的ts(2695)错误,是因为代码里用了逗号运算符——这个运算符只会返回最后一个表达式的值,左边的rounded-xl shadow-md完全被忽略了,既不会生效,还被TS判定为无用代码。
下面是两种正确的写法:
方法1:模板字符串拼接
直接把固定类名和条件类名用模板字符串拼接,最直观:
<button className={`rounded-xl shadow-md ${addRing ? 'ring-black' : 'ring-white'}`}> Button name </button>
方法2:数组转字符串(适合多条件场景)
把所有类名放进数组,再用join(' ')转成空格分隔的字符串,可读性更强:
<button className={[ 'rounded-xl shadow-md', addRing ? 'ring-black' : 'ring-white' ].join(' ')}> Button name </button>
如果之后需要加更多条件类,比如根据状态切换背景色,数组写法会更容易维护:
<button className={[ 'rounded-xl shadow-md', addRing ? 'ring-black' : 'ring-white', isActive ? 'bg-blue-500 text-white' : 'bg-gray-300 text-gray-800' ].join(' ')}> Button name </button>
内容的提问来源于stack exchange,提问作者Travis
相关产品推荐
相关产品推荐

