样式组件的多个道具选项 [英] Multiple Props Options for Styled Components
问题描述
我有一个使用样式化组件创建的导航栏组件.我想创建一些改变背景颜色和/或文本颜色的道具.
I have a navbar component that I have created using Styled Components. I would like to create some props that change the background-color and/or text color.
例如:
应具有以下 CSS:
For instance: <Navbar dark>
should have the following CSS:
background: #454545;
color: #fafafa;
而
应该是相反的:
background: #fafafa;
color: #454545;
但是,如果两个 prop 都没有使用,那么我想要一个默认的背景和文本颜色——比如说(为了演示目的),像这样:
If, however, neither prop is used, then I want to have a default background and text color -- say (for demo purposes), something like this:
background: #eee;
color: #333;
现在,我的问题是如何在 Styled Components 中进行设置.
Now, my question is how to set this up in Styled Components.
我可以执行以下操作:
background: ${props => props.dark ? #454545 : '#eee'}
background: ${props => props.dark ? #fafafa : '#eee'}
background: #eee;
还有类似的颜色.
但这是多余的,不是很优雅.我想要某种 if/else 语句:
But this is redundant and not very elegant. I would like some sort of if/else statement:
background: ${ props => {
if (props.dark) { #454545 }
elseif (props.light) { #fafafa }
else { #eee }
}
但我不知道如何在 Styled Components 中设置类似的东西.
But I don't know how to set something like that up in Styled Components.
有什么建议吗?
提前致谢.
推荐答案
这是我最终使用的解决方案:
This is the solution I ended up using:
export const Navbar = styled.nav`
width: 100%;
... // rest of the regular CSS code
${props => {
if (props.dark) {
return `
background: ${colors.dark};
color: ${colors.light};
`
} else if (props.light) {
return `
background: ${colors.light};
color: ${colors.dark};
`
} else {
return `
background: ${colors.light};
color: ${colors.dark};
`
}
}}
`
这篇关于样式组件的多个道具选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!