【问题标题】:React use theme variables inside styled from styled-componentsReact 在 styled-components 样式中使用主题变量
【发布时间】:2020-02-13 04:03:43
【问题描述】:

目前我正在尝试使用样式组件和样式系统制作主题。 我创建了一个包含我需要的所有样式的主题 (theme.js),一个带有样式组件和变体的 button.jsx。

在我的 theme.js 中是颜色,并且有一个带有颜色的模式(深色)。

//default
500: "#139ebe",

//modes
modes: {
  dark: {
    blues: {
      500: "white"
    }
  }
}

这些正在合并到一个主题对象中。

const getTheme = mode =>
  merge({}, theme, {
    colors: get(theme.colors.modes, mode, theme.colors)
  });

当模式为暗时,它应该从暗模式获取颜色。当没有模式时,它应该得到正常的颜色。

通过 props 我可以访问当前主题(参见 button.jsx 第 77 行)。

const Button = props => {
  console.log("Current theme: ", props.theme.colors.blues[500]);
  return <ButtonElem as="button" {...props} />;
};

在控制台中,您可以看到如果您移除暗模式,颜色变量会发生变化。对于按钮的样式,我需要相同的效果。如何从我的

中的主题提供程序访问正在使用的主题
const ButtonElem = styled("div")(

演示:

在codesandbox中打开控制台,你会看到当前的主题。删除暗模式并保存,然后您将看到更改。 https://codesandbox.io/s/blue-cache-bp9ns?fontsize=14

【问题讨论】:

  • '如何访问我的主题提供程序正在使用的主题' - 我不是 100% 确定我是否理解正确,但我访问样式组件 css 中当前变量的方式是color: ${props =&gt; props.theme.myVariable};。在此处阅读更多信息styled-components.com/docs/advanced#theming
  • 通常你会使用那个方法。现在它使用来自theme.js 的变量(这是静态的,因为它没有与暗模式对象合并)。这种方式不是选择。如果你去codesandbox和button.jsx(第79行)你可以看到你如何在改变主题模式的同时访问主题。 (检查控制台)props.theme.colors.blues[500] 我需要找到一种方法,以便我可以在 styled(div) 中访问props.theme.{variable}
  • 我想我可能已经发现了这个问题,如果你删除 styled() 的变体部分,它确实有效。现在我需要找到一种方法让它与变体一起工作
  • @SebastiaanvanArkens 找到了解决方案并将其发布为答案。我没有以正确的方式将道具传递给变体

标签: reactjs styling styled-components theming


【解决方案1】:

这是将道具传递给变体的正确方法

const type = props => (variant({

}));

【讨论】:

    猜你喜欢
    • 2021-08-26
    • 2021-07-13
    • 2018-02-09
    • 2018-04-29
    • 2022-01-04
    • 2018-01-19
    • 2018-10-20
    • 2020-08-31
    • 1970-01-01
    相关资源
    最近更新 更多