首页 > 解决方案 > 使用反应样式组件渲染多个样式类

问题描述

在我正在处理的步进器组件中,我使用的是 React Styled Components 库。不幸的是,我不能使用 Material UI 或其他类似的解决方案。最初,我使用 CSS 渲染步进器的所有 UI:

                        {index !== steps.length - 1 && (
                            <div
                                className={`divider-line divider-line_${steps.length}`}
                            />
                        )}

这行得通,但现在我必须使用这个库,所以我转换了我现在已经将水平线 CSS 转换为样式组件。

样式化的.js


export const DividerLine = styled.div`
    height: 1px;
    background-color: blue;
    position: absolute;
    top: 20%;
    left: 70%;
`;

export const DividerLine_2 = styled.div`
    width: 296%;
`;

export const DividerLine_3 = styled.div`
    width: 125%;
`;

export const DividerLine_4 = styled.div`
    width: 70%;
`;

export const DividerLine_5 = styled.div`
    width: 60%;
`;

其余的步进动画可以工作,但原始代码不会渲染水平线。

我在渲染各种状态的编号气泡时遇到了类似的问题,我通过创建要在内联样式中使用的变量来解决这个问题:

        let stepColor = '#65CC34';
        let stepText = '#ffffff';
        let stepTextActive = '#65CC34';

步进器.js


                <StepContainer key={index}>
                    <StepWrapper>
                        <StepNumber
                            style={{
                                background: `${
                                    step.selected ? stepColor : ''
                                }`,
                                color: `${
                                    step.selected ? stepText : stepTextActive
                                }`,
                            }}
                        >
                            {step.completed ? <span>&#10003;</span> : index + 1}
                        </StepNumber>
                        {index !== steps.length - 1 && (
                            <div
                                className={`divider-line divider-line_${steps.length}`}
                            />
                        )}
                    </StepWrapper>
                    <DividerLine />
                </StepContainer>
            );
        });

        return <StepWrapper>{stepsJSX}</StepWrapper>;
    }
}

但是,我不确定如何{`divider-line divider-line_${steps.length}`}在样式化组件内部使用。有什么建议么?

标签: javascriptcssreactjsstyled-components

解决方案


您不需要使用带有样式组件的多个类。以下是您的操作方法:

const dividerLineWidths = {
    '2': '296%',
    '3': '125%',
    '4': '70%',
    '5': '50%'
}

export const DividerLine = styled.div`
    height: 1px;
    background-color: blue;
    position: absolute;
    top: 20%;
    left: 70%;

    ${({steps}) => steps && `
      width: ${dividerLineWidths[steps.length]}
    `}
`;

然后:

...
{index !== steps.length - 1 && <DividerLine steps={steps} />}
...

样式化的组件将根据传递给它的 props 为您动态生成一个新的 className。将 styled-components consts 视为完整的组件,而不是 css 属性的 blob。


推荐阅读