【发布时间】:2021-05-12 07:45:26
【问题描述】:
我正在 React 中创建一个多步骤表单,它使用 switch case 根据其 ID 呈现组件:
App.js
function App() {
const steps = [
{ id: 'location' },
{ id: 'questions' },
{ id: 'appointment' },
{ id: 'inputData' },
{ id: 'summary' },
];
return (
<div className="container">
<ApptHeader steps={steps} />
<Step steps={steps} />
</div>
);
}
Steps.js
const Step = ({ steps }) => {
const { step, navigation } = useStep({ initialStep: 0, steps });
const { id } = step;
const props = {
navigation,
};
console.log('StepSummary', steps);
switch (id) {
case 'location':
return <StepLocation {...props} steps={steps} />;
case 'questions':
return <StepQuestions {...props} />;
case 'appointment':
return <StepDate {...props} />;
case 'inputData':
return <StepUserInputData {...props} />;
case 'summary':
return <StepSummary {...props} />;
default:
return null;
}
};
在我的 App.js 中的<ApptHeader /> 组件中,我想根据 switch case 中呈现的组件来更改标题中字符串的Title 和subtitle。
const SectionTitle = ({ step }) => {
console.log('step', step);
return (
<div className="sectionWrapper">
<div className="titleWrapper">
<div className="title">Title</div>
<div className="nextStep">
SubTitle
</div>
</div>
<ProgressBar styles={{ height: 50 }} />
</div>
);
};
export default SectionTitle;
我怎样才能做到这一点?如果我必须为每个标题/副标题再次制作一个 switch case,我觉得我可能会编写冗余代码。提前致谢。
【问题讨论】:
标签: javascript reactjs switch-statement