React多步表单基于switch case渲染时如何同步更新头部标题与副标题
实现方案
核心思路是把步骤元数据集中管理、状态提升共享,完全避免重复编写switch判断:
第一步:补全步骤元数据配置
直接在原来的steps数组里为每个步骤补充标题、副标题字段,所有步骤配置集中维护,后续新增/修改步骤只需要改这个数组:
// App.js中修改steps定义 const steps = [ { id: 'location', title: '选择服务地点', subtitle: '请选择你附近的可服务门店' }, { id: 'questions', title: '填写需求问卷', subtitle: '几个小问题帮我们更好适配你的需求' }, { id: 'appointment', title: '预约时间', subtitle: '选择你方便的到店时间' }, { id: 'inputData', title: '填写个人信息', subtitle: '请留下你的联系方式方便我们通知' }, { id: 'summary', title: '确认预约信息', subtitle: '请核对你提交的所有信息' }, ];
第二步:状态提升共享当前步骤
原来的useStep是在Step组件内部调用的,ApptHeader拿不到当前步骤状态,所以把这个hook调用移到App组件,父子组件共享状态:
// 修改后的App.js function App() { const steps = [ // 上面补全了title、subtitle的数组 ]; // 把useStep移到这里调用 const { step, navigation } = useStep({ initialStep: 0, steps }); return ( <div className="container"> {/* 把当前step传给Header */} <ApptHeader steps={steps} currentStep={step} /> {/* 把step和navigation传给Step组件 */} <Step step={step} navigation={navigation} /> </div> ); }
第三步:简化Step组件
现在Step组件不需要自己管理步骤状态了,直接接收props渲染对应组件即可,原有switch逻辑不需要调整:
// 修改后的Steps.js const Step = ({ step, navigation }) => { const { id } = step; const props = { navigation }; switch (id) { case 'location': return <StepLocation {...props} />; case 'questions': return <StepQuestions {...props} />; case 'appointment': return <StepDate {...props} />; case 'inputData': return <StepUserInputData {...props} />; case 'summary': return <StepSummary {...props} />; default: return null; } };
第四步:修改SectionTitle组件直接读取元数据
不需要任何判断逻辑,直接从传入的currentStep里取对应字段渲染:
const SectionTitle = ({ currentStep }) => { return ( <div className="sectionWrapper"> <div className="titleWrapper"> <div className="title">{currentStep.title}</div> <div className="nextStep"> {currentStep.subtitle} </div> </div> <ProgressBar styles={{ height: 50 }} /> </div> ); }; export default SectionTitle;
第五步:ApptHeader组件透传参数
在ApptHeader组件里接收currentStep props,直接传给SectionTitle即可:
// ApptHeader组件内部逻辑示例 const ApptHeader = ({ steps, currentStep }) => { // 保留原有其他逻辑 return <SectionTitle currentStep={currentStep} /> }
这个方案没有任何冗余的switch判断,所有步骤相关的配置都集中在steps数组里,后续迭代只需要维护这一个配置项即可。
内容的提问来源于stack exchange,提问作者Noble Polygon
相关产品推荐
相关产品推荐

