如何使用TypeScript基于后端JSON渲染Material Timeline并动态设置Paper背景色
实现方案
完全可以实现,以下是完整的TypeScript实现步骤和代码:
1. 先定义类型约束
import { LibraryBooks, PeopleAlt, BusinessCenter } from '@mui/icons-material'; // 审批步骤字段类型定义 interface IApprovalStep { approved: boolean; approvalTime: string; title: string; description: string; } // 后端返回的JSON结构类型 type IApprovalData = Record<string, IApprovalStep>; // 步骤对应图标映射,和你原有代码的图标顺序保持一致 const STEP_ICONS = [LibraryBooks, PeopleAlt, BusinessCenter];
2. 组件内逻辑与渲染
假设你已经通过接口拿到了后端返回的JSON数据,命名为approvalData,直接在组件内遍历渲染即可:
// 把后端返回的对象按step序号排序,避免对象遍历顺序异常导致展示错乱 const sortedSteps = Object.keys(approvalData) .sort((a, b) => parseInt(a.replace('step', '')) - parseInt(b.replace('step', ''))) .map(key => approvalData[key]); return ( <Timeline align="alternate"> {sortedSteps.map((step, index) => { const StepIcon = STEP_ICONS[index]; const isLastStep = index === sortedSteps.length - 1; return ( <TimelineItem key={`step-${index}`}> <TimelineOppositeContent> <Typography variant="body2" color="textSecondary"> {step.approvalTime} </Typography> </TimelineOppositeContent> <TimelineSeparator> <TimelineDot color={index === 0 ? 'inherit' : 'primary'}> <StepIcon /> </TimelineDot> {/* 最后一个节点隐藏连接线,符合常规时间线交互逻辑 */} {!isLastStep && <TimelineConnector />} </TimelineSeparator> <TimelineContent> <Paper elevation={3} className={classesTimeline.paper} // 动态设置背景色,approved为true时设为浅绿色,可自行调整色值 sx={{ backgroundColor: step.approved ? '#d4edda' : 'inherit' }} > <Typography variant="h6" component="h1"> {step.title} </Typography> <Typography>{step.description}</Typography> </Paper> </TimelineContent> </TimelineItem> ) })} </Timeline> )
补充说明
如果不需要保留原来的硬编码图标顺序,也可以把图标字段补充到后端返回的JSON结构里,实现更灵活的配置。
内容的提问来源于stack exchange,提问作者Peter Penzov
相关产品推荐
相关产品推荐

