我有这样的react组件:
const StyledMenu = () => {
const [currentStep, setCurrentStep] = React.useState('template');
const steps = ['template', 'audience', 'demography', 'action'];
const goToNextStep = () => {
const index = steps.indexOf(currentStep);
setCurrentStep(steps[index + 1]);
};
const goToPreviousStep = () => {
const index = steps.indexOf(currentStep);
if (index === 0) {
return;
}
setCurrentStep(steps[index - 1]);
};
return(
<div>
<StepsWrapper>
{steps.map((step, index) => (
<Step key={step} active={step === currentStep} last={index === 3}>
<StepDescription>{step}</StepDescription>
</Step>
))}
</StepsWrapper>
</div>
)
}
const StepsWrapper = styled('div')`
display: grid;
grid-template-columns: repeat(4, 1fr);
width: 100%;
height: 69px;
line-height: 69px;
text-align: center;
position: relative;
top: 27px;
`;
const Step = styled('div')<{ active: boolean; last: boolean }>`
color: ${({ active }) =>
active ? '#44b3db' : '#c7e8f4'};
`;
const StepDescription = styled('div')`
width: 240px;
height: 29px;
font-family: Roboto;
font-size: 18px;
font-weight: 500;
font-style: normal;
letter-spacing: normal;
line-height: normal;
text-align: center;
text-transform: uppercase;
margin: 0 auto;
`;我正在尝试设置活动项之前的项的样式。如果第一个项目处于活动状态,则不会设置任何样式。我想要从这些图像中实现样式:

和

和

我如何才能做到这一点?提前感谢!
发布于 2021-08-31 16:55:06
我通过为活动索引添加一个新的状态来实现这一点,如果活动索引大于索引,我将布尔值发送到样式组件,因此小于当前活动索引的索引的样式将与上面注释中提到的@vishnu不同。代码现在看起来像这样
const StyledMenu = () => {
const [currentStep, setCurrentStep] = React.useState('template');
const steps = ['template', 'audience', 'demography', 'action'];
//added this line of code
const [activeIndex, setActiveIndex] = React.useState(0);
const goToNextStep = () => {
const index = steps.indexOf(currentStep);
setCurrentStep(steps[index + 1]);
//set the new activeIndex
setActiveIndex(index + 1);
};
const goToPreviousStep = () => {
const index = steps.indexOf(currentStep);
if (index === 0) {
return;
}
setCurrentStep(steps[index - 1]);
//set the new activeIndex
setActiveIndex(index - 1);
};
return(
<div>
<StepsWrapper>
{steps.map((step, index) => (
//sending the checked props to the styled component
<Step key={step} active={step === currentStep} last={index
=== 3} checked={activeIndex > index}>
<StepDescription>{step}</StepDescription>
</Step>
))}
</StepsWrapper>
</div>
)
}
const StepsWrapper = styled('div')`
display: grid;
grid-template-columns: repeat(4, 1fr);
width: 100%;
height: 69px;
line-height: 69px;
text-align: center;
position: relative;
top: 27px;
`;
const Step = styled('div')<{ active: boolean; last: boolean;
checked: boolean }>`
//checking if component is marked to be styled differently
color: ${({ active, checked }) =>
active ? '#44b3db' : checked ? 'red' '#c7e8f4'};
`;
const StepDescription = styled('div')`
width: 240px;
height: 29px;
font-family: Roboto;
font-size: 18px;
font-weight: 500;
font-style: normal;
letter-spacing: normal;
line-height: normal;
text-align: center;
text-transform: uppercase;
margin: 0 auto;
`;https://stackoverflow.com/questions/69001927
复制相似问题