javascript - 使用反应样式组件渲染多个样式类
问题描述
在我正在处理的步进器组件中,我使用的是 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>✓</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}`}
在样式化组件内部使用。有什么建议么?
解决方案
您不需要使用带有样式组件的多个类。以下是您的操作方法:
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。
推荐阅读
- mysql - 如何进行自动 MySQL 数据库备份?
- pointers - 如何计算画布中的鼠标指针位置?
- swift - 带有基本身份验证的 RestApi 问题
- ios - 如何使用 Swift 以编程方式将 BLE 设备(nRF 52840)与 iOS iPhone 配对
- python - 如何在 2 个数据帧的 3 列中找到最接近的值?
- html - 使用 :after 选择性进行内联样式设置
- javascript - Why is this template not working correctly?
- r - XGBoost 的折叠规范不正确
- azure - 使用来自不同订阅的 Azure AD 的 Azure 应用服务
- c - 试图从标准中理解有符号整数转换规则