如何在样式组件中有条件地使用变量
我试图有条件地更改样式组件中组件的 UI,但我发现自己经常重复自己。 这就是现在正在发生的事情:
color: ${props => (props.isProductPage ? color('white') : 'reset')};
background-color: ${props =>
props.isProductPage ? color('primary', 'main') : 'reset'};
font-size: ${props => (props.isProductPage ? '1.4rem' : 'reset')};
font-weight: ${props => (props.isProductPage ? '400' : 'reset')};
但我想将所有这些都放在一个变量中并有条件地导入该变量,但我无法找出我做错了什么。这就是我正在寻找的。
const ProductPageAddToCard = `
color: ${color('primary')};
background: ${color('primary', 'main')};
font-size: ${textSize('medium')};
font-weight: ${textWeight('medium')}
`;
export const StyledAddToCardWrapper = Styled.div`
button {
${props => (props.isProductPage ? ProductPageAddToCard : '')}
}
`
提前致谢
I am trying to conditionally change the UI of my component in styled components, but I found myself repeating myself a lot.
this is what is happening right now:
color: ${props => (props.isProductPage ? color('white') : 'reset')};
background-color: ${props =>
props.isProductPage ? color('primary', 'main') : 'reset'};
font-size: ${props => (props.isProductPage ? '1.4rem' : 'reset')};
font-weight: ${props => (props.isProductPage ? '400' : 'reset')};
but I want to have all these in a variable and import that variable conditionally, but I could not find out what am I doing wrong. This is what I am looking for.
const ProductPageAddToCard = `
color: ${color('primary')};
background: ${color('primary', 'main')};
font-size: ${textSize('medium')};
font-weight: ${textWeight('medium')}
`;
export const StyledAddToCardWrapper = Styled.div`
button {
${props => (props.isProductPage ? ProductPageAddToCard : '')}
}
`
Thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用“styled-components”中的“css”导出来创建可重用的 mixin。
这是一个小例子:
You can use the 'css' export from 'styled-components' to create a reusable mixin.
Here is a small example: