[英]Update string based on switch case
我正在 React 中創建一個多步驟表單,它使用 switch case 根據其 ID 呈現組件:
應用程序.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>
);
}
步驟.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 中呈現的組件更改 header 中字符串的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,我覺得我可能會編寫冗余代碼。 提前致謝。
你可以使用這樣的模式
const steps = {
location: { id: 'location', title: 'Location', component: StepLocation },
questions: { id: 'questions', title: 'Questions', component: StepQuestions },
appointment: { id: 'appointment', title: 'Appointment', component: StepDate },
inputData: { id : 'inputData', title: 'InputData', component: StepUserInputData },
summary: { id: 'summary', title: 'Summary', component: StepSummary },
};
然后在您的Steps.js
中使用它時將變為
const Step = ({ steps }) => {
const { step, navigation } = useStep({ initialStep: 0, steps });
const { id } = step;
const props = { navigation };
const Component = steps[id].component;
return <Component {...props} steps={steps} />;
};
你的SectionTitle.js
會變成這樣
const SectionTitle = ({ step }) => {
console.log('step', step);
return (
<div className="sectionWrapper">
<div className="titleWrapper">
<div className="title">Title</div>
<div className="nextStep">{step.title}</div>
</div>
<ProgressBar styles={{ height: 50 }} />
</div>
);
};
export default SectionTitle;
這樣可以避免代碼冗余。
請務必更新代碼的其他部分,例如useStep
以接受和Object
而不是和Array
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.