如何在样式组件中有条件地使用变量

发布于 2025-01-12 00:44:14 字数 786 浏览 0 评论 0原文

我试图有条件地更改样式组件中组件的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

你是暖光i 2025-01-19 00:44:14

您可以使用“styled-components”中的“css”导出来创建可重用的 mixin。
这是一个小例子:

import styled, { css } from "styled-components";

// ...

const ProductPageMixin = css`
  color: red;
  background-color: orange;
`;

const HomePageMixin = css`
  color: blue;
  background-color: yellow;
`;

const Wrapper = styled.div`
  ${(props) => props.isProductPage && ProductPageMixin}

  ${(props) => props.isHomePage && HomePageMixin}
`;

You can use the 'css' export from 'styled-components' to create a reusable mixin.
Here is a small example:

import styled, { css } from "styled-components";

// ...

const ProductPageMixin = css`
  color: red;
  background-color: orange;
`;

const HomePageMixin = css`
  color: blue;
  background-color: yellow;
`;

const Wrapper = styled.div`
  ${(props) => props.isProductPage && ProductPageMixin}

  ${(props) => props.isHomePage && HomePageMixin}
`;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文