ReactJS中无法通过switch语句渲染类名,报buttonColour未定义错误
问题根源:你写的立即执行函数里的buttonColour是函数内部的局部变量,函数执行完后变量就会被销毁,外部的JSX代码根本无法访问到这个变量,所以会触发未定义错误。
下面给两种可行的解决办法:
方法一:正确获取立即执行函数的返回值
把立即执行函数的返回值赋值给外部的buttonColour变量,同时简化switch逻辑,直接返回对应的类名即可:
const buttonColour = (() => { switch (paymentstatus) { case "Paid": return "bg-green-100 text-green-800" case "Pending": return "bg-yellow-100 text-yellow-800" case "Failed": return "bg-red-100 text-red-800" default: return "" // 增加默认值,处理未匹配到的支付状态 } })() <td className="whitespace-nowrap px-3 py-4 text-sm text-gray-500"> <span className={`${buttonColour} inline-flex items-center rounded-md px-2.5 py-0.5 text-sm font-medium`}>{paymentstatus}</span> </td>
方法二:用对象映射替代switch(更简洁易维护)
直接创建一个支付状态与样式类名的映射对象,通过键值对直接取值,代码结构更清爽:
const statusClassMap = { Paid: "bg-green-100 text-green-800", Pending: "bg-yellow-100 text-yellow-800", Failed: "bg-red-100 text-red-800" } const buttonColour = statusClassMap[paymentstatus] || "" <td className="whitespace-nowrap px-3 py-4 text-sm text-gray-500"> <span className={`${buttonColour} inline-flex items-center rounded-md px-2.5 py-0.5 text-sm font-medium`}>{paymentstatus}</span> </td>
两种方法都能解决变量未定义的问题,第二种写法后续新增支付状态时,只需在映射对象里添加对应的键值对即可,维护成本更低。
内容的提问来源于stack exchange,提问作者BigJobbies
相关产品推荐
相关产品推荐

