在NextJS中,我试图将静态css类和条件类应用于元素。如果分开使用,我可以使两者都工作,但是当它们结合使用时,就会导致意想不到的错误。
# This will work
<span className="font-medium">{message}</span>
# This will work too
<span className={status ? "bg-green-600":"bg-orange-600"}>{message}</span>
在Visual Studio中,下面的代码片段将给出错误',' expected.ts(1005)
# This (where I'm trying to apply *both* classes to the same element) won't work
<span className={"font-medium" + {status ? "bg-green-600":"bg-orange-600"}}>{message}</span>
忽略它会产生以下错误:
Error:
x An object member cannot be declared optional
在font-medium后面需要一个空格,否则它将被解释为单个类
<span className={"font-medium " + status ? "bg-green-600":"bg-orange-600"}>{message}</span>
和模板字面值:
<span className={'font-medium ${status ? "bg-green-600" : "bg-orange-600" }'}>{message}</span>
(请注意这里是"而不是")
在这种情况下,不要忘记通过检查元素和检查类来进行调试
您也可以使用backtick(')作为替代
<span className=`font-medium ${status ? 'bg-green-600' : 'bg-orange-600' `}>{message}</span>