我正在尝试使用以下方法以免引起内存过载:
${MediaXS} {
font-size: 0.77rem;
}
不是使用下面的这种方法,而是因为它是一个数组,这会导致内存问题:
$ {MediaXS`
color: red
`}
但是我不知道导出与第一个示例一起使用的正确方法,我该怎么办?
我的代码:
import { css } from "styled-components";
export const MediaXS = css`
@media only screen and (min-width: 320px) {
}
`;
export const MediaSM = css`
@media only screen and (min-width: 576px) {
}
`;
export const MediaMD = css`
@media only screen and (min-width: 768px) {
}
`;
export const MediaLG = css`
@media only screen and (min-width: 992px) {
}
`;
export const MediaXL = css`
@media only screen and (min-width: 1200px) {
}
`;
答案 0 :(得分:0)
我相信您可以执行以下操作:
// configure screen width thresholds
const ScreenSizes = {
DESKTOP: 992,
TABLET: 768,
PHONE: 576
}
const sizes = {
desktop: ScreenSizes.DESKTOP,
tablet: ScreenSizes.TABLET,
phone: ScreenSizes.PHONE
}
// iterate through sizes and create a media template
const media =
Object
.keys(sizes)
.reduce((acc, label) => {
acc[label] = (...args) => css`
@media (max-width: ${sizes[label] / 16}em) {
${css(...args)}
}
`
return acc
}, {});
// use media methods with styled-component instead of raw @media queries
const StyledContent = styled.div`
width: 100%
${media.desktop`
padding: 10px;
`}
${media.tablet`
padding: 15px;
max-width: 700px;
`}
${media.phone`
padding: 20px;
max-width: 900px;
`}
`;
export class Content extends React.Component {
render() {
return (
<StyledContent>
{ this.children }
</StyledContent>
);
}
}
Ross Bulat 的信用,摘自本文: https://medium.com/@rossbulat/creating-themes-in-react-with-styled-components-6fce744b4e54