我无法让媒体查询与媒体模板和样式化的组件一起使用。我直接从文档定义了MediaQueries模板:
components: { // delete this code
security: Security
},
这是测试文件:
import { css } from "styled-components";
const sizes = {
desktop: 992,
tablet: 768,
phone: 576
};
// Iterate through the 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;
}, {});
export default media;
我期望的是[Desktop]标题显示在大屏幕上,而[Mobile]标题显示在较小的屏幕上。
我得到的是相反的结果:我同时在大屏幕上获得两个标题,然后在缩小窗口的同时,[Mobile]首先消失,然后[Desktop]消失。
我的目标是始终使一个组件只有一个可见。我在做什么错了?
答案 0 :(得分:2)
我认为您混合了规则。如果要根据大小切换它们,则其中之一应以display:none
开始,然后进行切换。
类似的东西:
const Desktop = styled.h1`
color: red;
${media.phone`
display: none;
`}
`;
const Mobile = styled.h1`
color: blue;
display: none;
${media.phone`
display: block;
`}
`;