【问题标题】:Media Queries in Emotion Styled Components情感风格组件中的媒体查询
【发布时间】:2020-04-20 11:14:10
【问题描述】:

Emotion 文档告诉我们如何 make reusable media queries 在 css 道具中工作。这允许我们在 css prop 中进行以下查询:

<div
  css={{
    color: 'green',
    [mq[0]]: {
      color: 'gray'
    },
    [mq[1]]: {
      color: 'hotpink'
    }
  }}
>

mq[0]mq[1] 指的是断点数组中的前两项。例如:const breakpoints = [576, 768, 992, 1200]

更重要的是,this article 更进一步,展示了如何使用断点对象获取命名的可重用媒体查询。它首先根据情感文档创建一个类似的函数,但针对对象:

const mq = n => {
  const bpArray = Object.keys(bp).map(key => [key, bp[key]]);

  const [result] = bpArray.reduce((acc, [name, size]) => {
    if (n === name) return [...acc, `@media (min-width: ${size}px)`];
    return acc;
  }, []);

  return result;
};

这允许我们创建一个带有命名媒体查询的断点对象:

// object
const breakpoints = {
  sm: 500,
  md: 768,
  lg: 992,
  xl: 1200
};


// query
${mq('sm')} { 
  color: gray;
}

到目前为止,一切都很好。

我现在想在情感风格的组件中做类似的事情。因此,我创建了一个断点对象和与上述文章中提到的相同的函数。

然后我尝试在我的情感样式组件中使用速记媒体查询——就像这样:

import styled from '@emotion/styled'

const Container = styled.div`
  ${mq('sm')`max-width: 750px;`}
  ${mq('md')`max-width: 970px;`}
  ${mq('lg')`max-width: 1170px`}
`

但是当我尝试这个时,它不起作用。我收到以下错误消息:

TypeError: Object(...) is not a function

知道为什么会发生这种情况以及我可以做些什么来让它发挥作用吗?

谢谢。

【问题讨论】:

  • ${mq('sm')} {max-width: 750px;}?
  • 谢谢——成功了。

标签: javascript reactjs emotion css-in-js


【解决方案1】:

为了澄清,OP 发布的内容主要存在轻微的语法错误(插值字符串中不应有额外的反引号)。

包含类型注释的完整代码示例如下所示:

const breakpoints: { [index: string]: number } = {
  sm: 500,
  md: 768,
  lg: 992,
  xl: 1200,
};

const mq = Object.keys(breakpoints)
  .map((key) => [key, breakpoints[key]] as [string, number])
  .reduce((prev, [key, breakpoint]) => {
    prev[key] = `@media (min-width: ${breakpoint}px)`;
    return prev;
  }, {} as { [index: string]: string });

const Container = styled.div`
  ${mq["sm"]} {
    max-width: 750px;
  }
  ${mq["md"]} {
    max-width: 970px;
  }
  ${mq["lg"]} {
    max-width: 1170px;
  }
`;

【讨论】:

    猜你喜欢
    • 2016-02-15
    • 2018-02-01
    • 2020-11-24
    • 2021-09-30
    • 2021-08-25
    • 2019-02-05
    • 1970-01-01
    • 2019-04-16
    • 2020-04-14
    相关资源
    最近更新 更多