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

如何在React.js Material UI Stepper步骤进度条中实现条件渲染?

实现方案

核心逻辑说明

你之前的条件判断不生效,大概率是直接套用了MUI官方示例的activeStep线性控制逻辑,非线性独立节点的Stepper不需要全局激活序号,每个节点的完成状态单独绑定对应判断条件即可。

步骤1:定义步骤配置与状态计算

首先在组件内定义所有6个节点的配置,包含每个节点的显示文案和独立完成条件:

import { Stepper, Step, StepLabel, Box, Typography, Card, CardContent } from '@mui/material';
import { connect } from 'react-redux';
// 你已有的get工具函数如果是lodash的可以正常用,这里直接对应props参数

const TOTAL_STEPS = 6;

// 步骤配置,每个项独立定义完成判断规则
const stepConfigs = [
  {
    label: '完成身份验证',
    // 直接用props传入的Redux状态判断
    isCompleted: (props) => props.isAuthenticated
  },
  {
    label: '完成用户问卷',
    isCompleted: (props) => !!props.quiz // 问卷存在即为完成,可根据实际业务调整判断条件
  },
  {
    label: '上传用户头像',
    isCompleted: (props) => !!props.profilePicture // 头像ID存在即为完成
  },
  // 剩余3个节点按业务规则补充配置即可
  {
    label: '补充个人信息',
    isCompleted: (props) => /* 你的业务判断条件 */ false
  },
  {
    label: '绑定联系方式',
    isCompleted: (props) => /* 你的业务判断条件 */ false
  },
  {
    label: '完成实名认证',
    isCompleted: (props) => /* 你的业务判断条件 */ false
  }
];

步骤2:组件主体实现

在组件内计算完成度和每个节点的状态,直接渲染Stepper:

function ProfileProgressCard(props) {
  // 计算每个步骤的完成状态
  const stepStates = stepConfigs.map(config => config.isCompleted(props));
  // 计算总完成率,向下取整刚好符合1/6=16%的示例效果
  const completedCount = stepStates.filter(Boolean).length;
  const progressPercent = Math.floor((completedCount / TOTAL_STEPS) * 100);

  return (
    <Card sx={{ maxWidth: 800, margin: '20px auto' }}>
      <CardContent>
        <Typography variant="h6" gutterBottom>
          你的资料已完成{progressPercent}%!
        </Typography>
        <Box sx={{ width: '100%', padding: '20px 0' }}>
          <Stepper nonLinear activeStep={-1} sx={{ padding: 0 }}>
            {stepConfigs.map((config, index) => (
              <Step key={index} completed={stepStates[index]}>
                <StepLabel>{config.label}</StepLabel>
              </Step>
            ))}
          </Stepper>
        </Box>
      </CardContent>
    </Card>
  );
}

// 你已有的mapStateToProps和mapDispatchToProps直接使用即可
const mapStateToProps = state => {
  const { profile, user } = state.Login;
  const quiz = get(profile,'userData.quiz');
  const profilePicture = get(profile,'userData.profilePictureId');
  return {
    profile,
    isAuthenticated: !!user.accessToken,
    quiz,
    profilePicture 
  };
};
const mapDispatchToProps = {
  action
};

export default connect(mapStateToProps, mapDispatchToProps)(ProfileProgressCard);

关键调整说明

  • 给Stepper设置nonLinear属性和activeStep={-1},关闭默认的线性激活逻辑,不会有默认的高亮节点
  • 每个Step的completed属性直接绑定独立判断的结果,不受前序节点状态影响,满足「已上传头像但未完成问卷时节点3仍可标记为完成」的需求
  • 完成百分比自动根据完成的节点数量计算,无需手动维护
    你可以根据实际业务需求调整每个步骤的isCompleted判断逻辑,比如问卷需要提交成功才算完成、头像需要审核通过才算完成等,只需要修改对应配置项的判断函数即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 07:39:04