【问题标题】:Styled components arithmetic operations样式化的组件算术运算
【发布时间】:2026-01-25 21:55:05
【问题描述】:

我有一个演示 here

它是一个简单的反应应用程序,我在其中使用带有主题的样式化组件

主题是这样的

import { DefaultTheme } from "styled-components";

export const theme: DefaultTheme = {
  sizes: {
    height: "50px",
    width: "50px"
  }
};

是否可以在样式化组件中将主题值与算术运算一起使用

类似

height: ${({ theme }) => theme.sizes.height}+
    ${({ theme }) => theme.sizes.height};
    

这在我的演示中不起作用,但我不知道语法是不正确还是不可能。

【问题讨论】:

  • "50px" + "50px" = "50px50px".

标签: reactjs styled-components


【解决方案1】:

要应用这个,你的主题应该是这样的,道具将是数字,而不是字符串。

export const theme: DefaultTheme = {
  sizes: {
    height: 50,
    width: 50
  }
};

所以你现在可以设置你的高度了。

height: ${({ theme }) => theme.sizes.height + theme.sizes.height};

【讨论】:

  • 我认为可能是这种情况,但我无法更改主题。当前主题有没有办法
  • 如果您绝对确定它始终是带有“px”后缀的字符串,您可以只修剪最后两个字符并将结果转换为整数。但是很hacky..我认为我实际上不建议这样做。但这是可能的。
  • 我确实像height: ${({ theme }) => theme.sizes.height.replace("px", "")}+ ${({ theme }) => theme.sizes.height.replace("px", "")};这样尝试过
  • 为什么要在两个函数中做呢?我不熟悉样式化的组件,但从一个看起来不正确的普通 JS 角度来看。将它放在一个函数中,就像这里的答案一样。您还错过了“将结果转换为整数”部分。即使在单个函数中,我想这也会导致“5050”。