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

如何将Mui Stepper完成步骤的对勾图标替换为步骤编号

替换Material-UI v4 Stepper完成步骤的对勾图标为对应编号

问题说明

在React项目中使用material-ui@4.11.3版本的Stepper组件时,已完成的步骤默认显示对勾图标,需将其替换为对应步骤的编号,同时保留现有样式。

当前效果

当前效果:完成步骤显示对勾图标

期望效果

期望效果:完成步骤显示对应编号

解决方案

Material-UI v4的StepLabel组件支持通过StepIconComponent属性自定义步骤图标,我们可以创建一个自定义组件,根据步骤状态渲染编号而非默认对勾,同时复用原有样式类。

1. 创建自定义StepIcon组件

import classNames from 'classnames';

const CustomStepIcon = ({ active, completed, index, classes }) => {
  // 步骤编号从1开始计数
  const stepNumber = index + 1;
  return (
    <div 
      className={classNames(
        classes.icon,
        { [classes.activeIcon]: active },
        { [classes.completedIcon]: completed }
      )}
    >
      {stepNumber}
    </div>
  );
};

2. 修改Stepper组件代码

将原StepLabel中的StepIconProps替换为StepIconComponent,传入自定义组件:

<Stepper
  style={{ background: 'transparent', width: '100%' }}
  activeStep={activeStep}
  alternativeLabel
>
  {steps.map((x, index) => ( // 新增index参数用于计算步骤编号
    <Step key={x.label}>
      <StepButton 
        disabled={!onStepAction || x.order > activeStep}
        onClick={() => onStepAction(x.order)}
      >
        <StepLabel
          classes={{
            label: classes.label,
            active: classes.activeLabel,
            completed: classes.completedLabel,
          }}
          // 替换为自定义图标组件
          StepIconComponent={(props) => <CustomStepIcon {...props} classes={classes} />}
        >
          {x.label}
        </StepLabel>
      </StepButton>
    </Step>
  ))}
</Stepper>

3. 调整样式配置

移除原样式中针对SVG文本的规则,添加布局样式确保编号居中:

const styles = theme => ({
  root: {},
  icon: {
    borderRadius: "50%",
    border: "2px solid #ffffff",
    transform: "scale(1.2)",
    color: colorMap.white,
    // 添加布局样式,确保编号居中显示
    width: 24,
    height: 24,
    display: "flex",
    alignItems: "center",
    justifyContent: "center",
    fontSize: theme.typography.pxToRem(14),
    '&$activeIcon': {
      color: theme.palette.primary.main,
      backgroundColor: colorMap.white,
    },
    '&$completedIcon': {
      color: theme.palette.primary.main,
      backgroundColor: colorMap.white,
    },
  },
  activeIcon: {},
  completedIcon: {},
  label: {
    color: colorMap.white,
    '&$activeLabel': {
      fontWeight: 'bold',
      color: colorMap.white,
    },
    '&$completedLabel': {
      color: colorMap.white,
    },
  },
  activeLabel: {},
  completedLabel: {},
});

说明

  • 自定义组件通过index参数计算步骤编号,确保与步骤顺序一致
  • 复用原有icon、activeIcon、completedIcon样式类,完全保留原有视觉效果
  • 通过flex布局确保编号在圆形图标中居中显示

内容的提问来源于stack exchange,提问作者Moez Baccouche

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 10:10:49