You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何根据状态值动态更改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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 04:50:34