在主题内设置多个值

问题描述 投票:1回答:3

我目前发现样式组件和样式主题,我很好,我可以在主题内指定多个值。我会解释......

所以在示例中我们有这样的代码:

const boxBg = theme('mode', {
  light: '#fff',
  dark: '#000'
})

const Box = styled.div`
  background-color: ${boxBg};
`;

但我可以这样做吗?

const boxStyles = theme('mode', {
  light: {
    color: #000,
    bg: #fff
  }
  //...
})

const Box = styled.div`
  background-color: ${boxStyles.bg};
  color: ${boxStyles.color};
`;

我发现的一个解决方案是:

const Color = theme('mode', {
  //- styles for color })
const Bg = theme('mode', {
  //- styles for bg })

const Box = styled.div`
  background-color: ${Bg};
  color: ${Color };
`;

但它有点奇怪,只是想象你有4-5种不同的'模式'和4-5种不同的风格值。

styled-components
3个回答
0
投票

我一直在寻找相同的东西(不,这不是Simons0n所建议的)。我们想要的是形成主题的样式集合,而不是像许多示例那样的单属性主题。

幸运的是,我发现了这篇文章:https://jsramblings.com/2017/11/05/theming-with-styled-components.html,以及https://codesandbox.io/s/q0wxr0l4的配套实现和代码沙箱。

在那里,作者(Corina Udrescu)完全展示了我们想要的东西 - 分组为主题的样式,如:

const dayTheme = {
  skyColor: '#37d8e6',
  celestialObjectColor: '#ffdd00',
  celestialObjectBorderColor: '#f1c40f'
};

const nightTheme = {
  skyColor: '#2c3e50',
  celestialObjectColor: '#bdc3c7',
  celestialObjectBorderColor: '#eaeff2'
} 

然后按名称引用,如

const Sky = styled.div`
  height: 100%;
  width: 100%;
  background-color: ${props => props.theme.skyColor}
`

主要的样式组件文档也在主题为https://www.styled-components.com/docs/advanced#theming的地方展示了这一点

// Define our `fg` and `bg` on the theme
const theme = {
  fg: 'palevioletred',
  bg: 'white'
};

// This theme swaps `fg` and `bg`
const invertTheme = ({ fg, bg }) => ({
  fg: bg,
  bg: fg
});

但不幸的是,他们没有切换主题的好例子(只是有选择地应用)。正如Corina所示,使用状态来控制它们是动态主题切换的关键:

<ThemeProvider theme={this.state.theme}

0
投票

考虑多重“模式”真的很奇怪。

第一种选择是做类似的事情:

const boxStyles = theme('mode', {
  light: css`
    background: ${white};
    color: ${black};
  `,
  dark: css`
    background: ${black};
    color: ${white};
  `,
});

const Box = styled.div`
  ${boxStyles}
`;

我从style-theming official repo得到了这个例子

第二种选择是:

theme('mode', {
  light: '#fff',
  dark: '#000',
});

theme('font', {
  sansSerif: '"Helvetica Neue", Helvetica, Arial, sans-serif',
  serif: 'Georgia, Times, "Times New Roman", serif',
  monoSpaced: 'Consolas, monaco, monospace',
});

我从styled-theming official repo得到了一个例子

如果你注意到第二种选择,作者使用倍数'名称'来区别他想要主题的每个属性......

祝你今天愉快。


-1
投票

你正在寻找这样的东西吗?

const theme = {
    mainColor: 'green',
    mainBgColor: 'red'
};

const Button = styled.button`
  color: ${props => props.theme.mainColor};
  background-color: ${props => props.theme.mainBgColor};
`;

你不能做的是,在一个组件上放置多个主题。这也不会有多大意义,因为主题提供者应该用于设计应用程序的不同区域。喜欢,不应该有bgcolors的主题和字体颜色的一个主题。它应该是标题和页脚的主题,例如,bgcolor和字体颜色不同。

以下是关于主题的一些其他信息:https://www.styled-components.com/docs/advanced#theming

© www.soinside.com 2019 - 2024. All rights reserved.