如何根据状态值动态更改Typography组件的背景颜色?
动态切换文本背景色方案
你可以通过条件判断根据状态值动态设置背景颜色,直接在sx属性的backgroundColor中使用三元表达式即可实现需求:
修改后的代码如下:
<Typography sx={{ padding: 1, backgroundColor: recent.status === 'pending' ? 'yellow' : 'green' }}> {recent.status} </Typography>
如果后续需要扩展更多状态(比如新增failed状态用红色),用对象映射的方式会更便于维护:
const statusColors = { pending: 'yellow', complete: 'green', failed: 'red' }; <Typography sx={{ padding: 1, backgroundColor: statusColors[recent.status] || 'gray' }}> {recent.status} </Typography>
后续新增状态时,只需在statusColors对象里添加对应的键值对即可。
内容的提问来源于stack exchange,提问作者Stykgwar
相关产品推荐
相关产品推荐

