【问题标题】:Passing variables for media queries and rendering css in styled components?为媒体查询传递变量并在样式化组件中渲染 CSS?
【发布时间】:2021-05-18 07:18:21
【问题描述】:

我正在尝试在样式化组件中编写更强大的媒体查询版本。

我基本上定义了一个断点文件,我将相应的断点传递到另一个文件中,该文件在这里呈现:

const setMq = breakpoints => {
    return css` @media (min-width: ${breakpoints.from / 16}em) and (max-width: ${breakpoints.until / 16}em) {}`
};

然后在我的实际样式组件中,我试图调用它,但由于某种原因,我无法获得“蓝色”的新颜色来呈现?

const ButtonStyled = styled.button`
    color: red;

    ${(setMq({
        from: breakpoints.xs,
        until: breakpoints.l,
     }),
     `
        color: blue;
    `)};
`;

【问题讨论】:

  • 你能在控制台记录 setMq 结果吗?
  • 是的,所以我基本上返回一个css数组:["@media only screen and (min-width:", "36", "em) and (max-width:", "62" , "em){}"]。我猜我可能只需要返回没有打开和关闭 {} 的媒体查询行?

标签: css reactjs sass styled-components


【解决方案1】:

我正在使用带有样式组件的样式系统,我真的推荐它。我可以在全局 theme.ts 文件中定义断点(媒体查询)及其样式,而不是单独定义它,而且它运行良好(也可以跨组件重用)。 例如,我有

...
grid: {
        breakpoints: [375, 768, 1200],
        maxWidth: 1440,
    },
...

在我的 theme.ts 文件中,字体大小的变化取决于屏幕大小。比如

error: {
    fontSize: [11, 11, 14],
    fontWeight: "regular",
    lineHeight: ["14px", "14px", "18px"],
    fontFamily: "PT Sans, sans-serif",
    color: "#FF2222",
},

我认为在你的情况下,你可以应用类似的东西

color: ['red', 'red', 'blue']

https://www.npmjs.com/package/styled-components-breakpoint 有一个 npm 库 但你也可以使用样式系统的默认断点来响应https://styled-system.com/responsive-styles

【讨论】:

  • 感谢您的回复!所以我猜我的答案将是其中一些和您提供的链接的组合。我工作的公司的性质意味着他们只希望断点值是可变的。所以我几乎每次都需要在我的样式组件中调用一个“mixin”,然后传递我需要的任何 css。
  • 哦,是的,将断点作为变量调用应该不是问题。我想断点在组件之间是共享的,并且对于每个单独的组件没有不同。
【解决方案2】:

我想通了,其他需要解决方案的人,我需要将我的主要“函数”更改为不作为数组输出而是作为字符串返回:

const setMq = breakpoints => {
return style => 
    `@media only screen and (min-width: ${breakpoints.from / 16}em) and (max-width: ${breakpoints.until / 16}em) { ${style} }`;
};

然后调用:

const ButtonStyled = styled.button`
color: red;

${setMq({
    from: breakpoints.xs,
    until: breakpoints.l,
    })`color: blue;`};
`;

export { ButtonStyled };

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-04
    • 2020-04-14
    • 2023-03-10
    • 2019-03-19
    • 2021-10-29
    • 1970-01-01
    • 1970-01-01
    • 2012-10-15
    相关资源
    最近更新 更多