我正在尝试实现一个步进器。点击下一步,一切正常。但是如果我点击返回,状态不会直接改变。
PS:整个事情只是不工作在Chrome。在Edge中一切正常
const [activeStep, setActiveStep] = React.useState(0);
const handleBack = () => {
if (activeStep !== 1) {
setActiveStep((prev) => prev - 1);
}
};
const handleNext = () => {
setActiveStep(activeStep + 1);
}
return(
<Box sx={{ display: "flex", flexDirection: "row", pt: 2 }}>
<Button
color="inherit"
onClick={handleBack}
sx={{ mr: 1, display: activeStep > 1 ? "block" : "none" }}
>
back
</Button>
<Box sx={{ flex: "1 1 auto" }} />
<Button onClick={handleNext}>
{activeStep === steps.length - 1 ? "send" : "next"}
</Button>
</Box>
)
当activeStep
状态更新为值1
时,前一个按钮将不再减少活动步长值。我建议将activeStep
状态设置为activeStep - 1
和0
的最大值。在增加和减少activeStep
状态时使用功能状态更新。
的例子:
const handleBack = () => {
setActiveStep(step => Math.maximum(0, step - 1));
};
const handleNext = () => {
setActiveStep(step => Math.minimum(steps.length - 1, step + 1));
}
你可以让UI更进一步,当活动步骤是最后一步/第一步时禁用下一步/上一步按钮。
return (
<Box sx={{ display: "flex", flexDirection: "row", pt: 2 }}>
<Button
color="inherit"
disabled={activeStep === 0}
onClick={handleBack}
sx={{ mr: 1, display: activeStep > 1 ? "block" : "none" }}
>
back
</Button>
<Box sx={{ flex: "1 1 auto" }} />
<Button
disabled={activeStep === steps.length - 1}
onClick={handleNext}
>
{activeStep === steps.length - 1 ? "send" : "next"}
</Button>
</Box>
)