reactjs - 创建 Stepper,将 next 和 back 作为 onClick-event 处理
问题描述
我想创建一个步进器,您可以在其中将 StepLabel 中的 Next 和 handleBack 作为 onClickevent 处理。我不知道该怎么做。
这是沙箱:https ://codesandbox.io/s/stepper-forked-2q1wd
export default function IndexPage() {
const [activeStep, setActiveStep] = useState(0);
const handleNext = () => {
setActiveStep((prevActiveStep) => prevActiveStep + 1);
};
const handleBack = () => {
setActiveStep((prevActiveStep) => prevActiveStep - 1);
};
function getStepsContent(stepIndex) {
switch (stepIndex) {
case 0:
return <h1>adsf</h1>;
case 1:
return <h1>adsf</h1>;
case 2:
return <h1>adsf</h1>;
}
}
const steps = getSteps();
return (
<>
<div>
<Stepper
alternativeLabel
activeStep={activeStep}
connector={<ColorlibConnector />}
>
{steps.map((label) => (
<Step key={label}>
<StepLabel
onClick={handleNext}
StepIconComponent={ColorlibStepIcon}
>
{label}
</StepLabel>
</Step>
))}
</Stepper>
</div>
<br />
<div>
{getStepsContent(activeStep)}
{activeStep === steps.length ? (
"Bewerbung abgesendet"
) : (
<div style={{ display: "flex", justifyContent: "center" }}>
<div>
<Button
variant="outlined"
color="primary"
onClick={handleBack}
disabled={activeStep === 0}
>
{activeStep > 0 ? "Zurück" : null}
</Button>
<Button
style={{ color: "white", margin: 30 }}
variant="contained"
color="primary"
onClick={handleNext}
>
{activeStep === steps.length - 1 ? "Absenden" : "Weiter"}
</Button>
</div>
</div>
)}
</div>
</>
);
}
我刚刚将handleNext 函数添加为onClick,但我还想通过单击步进器返回。
解决方案
您可以使用索引来设置步骤。用这个替换你onClick
的StepLabel
{steps.map((label, index) => (
<Step key={label}>
<StepLabel
onClick={() => setActiveStep(index)}
StepIconComponent={ColorlibStepIcon}
>
{label}
</StepLabel>
</Step>
))}
推荐阅读
- mysql - 带有表情符号的 MySQL AES_ENCRYPT/AES_DECRYPT
- octave - 计数或只读实际条目
- vue.js - 通过脚本标签使用 vue.js 时的 Vue.js 插值
- javascript - 如果某事等于某事,则取消提示
- python - Django - SELECT 行相关子项的总和最大,GROUP BY 相关父项
- r - 在 R 中获取 ego 和 alter 的共同点数
- java - java服务器应用程序性能问题
- flutter - 如何在颤动中返回前2页
- javascript - 自动更改图像的轮播 [JS]
- c - 在 C 语言中,我可以使用 `<` 或 `>` 来比较指向 NULL 的指针吗?