如何自定义MUI Stepper组件的默认错误状态图标
MUI Stepper 自定义错误图标实现方案
效果参考
- 组件默认错误图标效果:

- 目标实现的错误图标效果:

核心问题说明
你之前配置不生效的核心原因是传参位置错误:StepIconComponent是StepLabel组件的一级接收属性,不需要嵌套在labelProps对象深层传递,直接挂载到StepLabel标签上即可被组件正确识别。
可直接落地的实现代码
方式1:单组件自定义(适合个别页面单独改样式)
自定义图标组件时只需要根据组件透传的error状态判断,返回对应样式的图标即可,非错误状态可以直接复用MUI默认的StepIcon,不需要重复写已完成、激活态的样式逻辑:
import * as React from 'react'; import Box from '@mui/material/Box'; import Stepper from '@mui/material/Stepper'; import Step from '@mui/material/Step'; import StepLabel from '@mui/material/StepLabel'; import MuiStepIcon from '@mui/material/StepIcon'; import Close from '@mui/icons-material/Close'; // 自定义图标组件,仅替换错误状态图标 const CustomStepIcon = (props) => { const { error, className } = props; // 错误状态返回目标样式:红色圆形底+白色叉号 if (error) { return ( <Box className={className} sx={{ width: 24, height: 24, borderRadius: '50%', backgroundColor: '#d32f2f', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff' }} > <Close sx={{ fontSize: 16 }} /> </Box> ); } // 其余状态直接复用默认图标 return <MuiStepIcon {...props} />; }; // 业务使用示例 const steps = ['提交申请', '信息校验', '审核完成']; export default function DemoStepper() { return ( <Box sx={{ width: '100%', padding: 3 }}> <Stepper activeStep={1}> {steps.map((label, index) => { const labelProps = {}; // 标记第二个步骤为错误状态 if (index === 1) labelProps.error = true; return ( <Step key={label}> {/* 直接传自定义图标组件即可,不要嵌套到labelProps里 */} <StepLabel StepIconComponent={CustomStepIcon} {...labelProps}> {label} </StepLabel> </Step> ); })} </Stepper> </Box> ); }
方式2:全局配置(适合项目内所有Stepper统一替换错误图标)
如果项目里所有步骤条都要用这套错误图标,直接在MUI主题配置里覆盖默认属性即可,不需要每个页面单独传参:
import { createTheme } from '@mui/material/styles'; const customTheme = createTheme({ components: { MuiStepLabel: { defaultProps: { StepIconComponent: CustomStepIcon } } } });
样式调整说明
如果需要匹配设计稿尺寸、色值,直接修改CustomStepIcon里错误状态分支的sx样式即可:
- 修改
width/height调整图标大小 - 修改
backgroundColor调整错误态底色 - 替换
Close图标为自己引入的SVG图标,即可完全匹配目标设计效果
内容的提问来源于stack exchange,提问作者Abdelkader
相关产品推荐
相关产品推荐

