为媒体查询传递变量并在样式组件中渲染css ?



我试图在样式组件中编写一个更健壮的媒体查询版本。

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

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;
`)};
`;

我正在使用样式化的系统和样式化的组件,我非常推荐这样做。我可以在全局theme.ts文件中定义断点(媒体查询)及其样式,而不是单独定义它,它工作得很好(也可以跨组件重用)。例如,我有

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

在我的主题。Ts文件和字体大小的变化取决于屏幕大小。如

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

我想就你的情况,你可以使用类似的

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

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

我明白了,谁需要解决方案,我需要改变我的主要功能"不作为数组输出,而是作为字符串返回:

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 };

最新更新