【问题标题】:How to Create Dynamic Media Queries with Styled-Components?如何使用样式化组件创建动态媒体查询?
【发布时间】:2020-06-23 21:05:02
【问题描述】:

我正在尝试使用以下方法来避免导致内存过载:

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

【问题讨论】:

    标签: reactjs styled-components


    【解决方案1】:

    我相信你可以这样做:

    // 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-10
      • 2020-04-14
      • 2021-10-29
      • 2023-03-22
      • 2022-01-04
      • 2019-12-25
      • 2019-10-11
      • 1970-01-01
      相关资源
      最近更新 更多