媒体查询不适用于 React App 中的样式化组件

Media queries not working with styled components in React App

我无法让媒体查询与媒体模板和样式化组件一起使用。我直接从文档中定义了一个 MediaQueries 模板:

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;

这是测试文件:

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;

我期望的是 [Desktop] 标题显示在大屏幕上,而 [Mobile] 标题显示在较小的屏幕上。

我得到的是相反的:我在大屏幕上同时获得两个标题,然后在缩小 window 时 [Mobile] 首先消失,然后 [Desktop]。

我的目标是让一个且只有一个组件始终可见。我做错了什么?

我认为您混淆了规则。如果你想根据大小切换它们,那么其中一个应该以 display:none 开头,然后你切换它们。

与此类似的内容:

const Desktop = styled.h1`
  color: red;

  ${media.phone`
    display: none;
  `}
`;

const Mobile = styled.h1`
  color: blue;
  display: none;
  ${media.phone`
    display: block;
  `}
`;