本文介绍了媒体查询不适用于 React App 中的样式组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我无法让媒体查询与媒体模板和样式组件一起使用.我直接从文档中定义了一个 MediaQueries 模板:
MediaQueries.js
import { css } from "styled-components";常量大小 = {桌面:992,平板电脑:768,电话:576};//遍历大小并创建媒体模板const media = Object.keys(sizes).reduce((acc, label) => {acc[label] = (...args) =>css`@media(最大宽度:${sizes[label]/16}em){${css(...args)}}`;返回acc;}, {});导出默认媒体;
这是测试文件:
App.js
从react"导入React;从样式组件"导入样式;从./MediaQueries"导入媒体;const 桌面 = styled.h1`红色;${media.phone`显示:无;`}`;const Mobile = styled.h1`颜色:蓝色;${media.desktop`显示:无;`}`;功能应用(){返回 (<div><移动>移动</移动><桌面>桌面</桌面>
);}导出默认应用程序;
我期待的是 [桌面] 标题显示在大屏幕上,而 [移动] 标题显示在小屏幕上.
我得到的是相反的:我在大屏幕上看到两个标题,然后在缩小窗口时[移动]先消失,然后是[桌面].
我的目标是让一个且只有一个组件始终可见.我做错了什么?
解决方案
我认为你把规则搞混了.如果您想根据大小切换它们,那么其中之一应该以 display:none
开头,然后切换它们.
类似的东西:
const Desktop = styled.h1`红色;${media.phone`显示:无;`}`;const Mobile = styled.h1`颜色:蓝色;显示:无;${media.phone`显示:块;`}`;
I'm having trouble getting media queries to work with media templates and styled components. I defined a MediaQueries template straight from the docs:
MediaQueries.js
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;
And here's the test file:
App.js
import React from "react";
import styled from "styled-components";
import media from "./MediaQueries";
const Desktop = styled.h1`
color: red;
${media.phone`
display: none;
`}
`;
const Mobile = styled.h1`
color: blue;
${media.desktop`
display: none;
`}
`;
function App() {
return (
<div>
<Mobile>Mobile</Mobile>
<Desktop>Desktop</Desktop>
</div>
);
}
export default App;
What I'm expecting is for the [Desktop] title to be shown on large screens, and [Mobile] to be shown on smaller ones.
What I'm getting is the opposite: I get both titles on large screens, then while shrinking the window [Mobile] disappears first, then [Desktop].
My goal is to have one and only one of the components visible at all times. What am I doing wrong?
解决方案
I think you got the rules mixed. If you want to toggle them based on size then one of them should start off with display:none
, then you switch them.
Something similar to this:
const Desktop = styled.h1`
color: red;
${media.phone`
display: none;
`}
`;
const Mobile = styled.h1`
color: blue;
display: none;
${media.phone`
display: block;
`}
`;
这篇关于媒体查询不适用于 React App 中的样式组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!