【问题标题】:React styled component media query not working with child elements?React 样式的组件媒体查询不适用于子元素?
【发布时间】:2020-12-08 02:45:06
【问题描述】:

所以我有这个样式组件,我在其中定位嵌套图像以单独定位它们。我想在主组件上添加一个媒体查询,但是当我在嵌套图像上方执行此操作时,它给了我一个语法错误。

这是我的样式化组件

      const ColumnRight = styled.div`
        display: flex;
        justify-content: center;
        align-items: center;
        padding: 2rem;
        position: relative;

        @media screen and (max-width: 768px) {
          height: 100vh;
        }

        ${Image}:nth-child (1) {
          top: 10px;
          left: 10px;
        }
        `

这段代码是导致我的错误的原因

      @media screen and (max-width: 768px) {
          height: 100vh;
        }

如果我这样做,它完全可以正常工作。

  const ColumnRight = styled.div`
        display: flex;
        justify-content: center;
        align-items: center;
        padding: 2rem;
        position: relative;

        ${Image}:nth-child (1) {
          top: 10px;
          left: 10px;
        }
        `

这是我尝试定位的组件

   <ColumnRight>
      <Image/>
   </ColumnRight>

为什么当我不包含媒体查询时它完全可以正常工作,但当我添加它时,它会导致语法错误?

更新:我发现问题是 prettier 在我保存时会随机向我的 nth-childs 添加一个空格,这会导致错误。

所以保存的代码最终会这样做

  nth-child  (1)

什么时候应该是nth-child(1)

知道为什么会发生这种情况以及如何预防吗?

【问题讨论】:

标签: reactjs styled-components


【解决方案1】:

试试这个怎么样?

  const ColumnRight = styled.div`
        display: flex;
        justify-content: center;
        align-items: center;
        padding: 2rem;
        position: relative;

        @media screen and (max-width: 768px) {
          height: 100vh;
        }

        > ${Image}:nth-child(1) {
          top: 10px;
          left: 10px;
        }
`

【讨论】:

  • 仍然无法正常工作。我添加了上面错误的图片
  • 实际上,每当我保存它时,它都会在第 n 个孩子和 (1) 之间添加一个空格,这就是发生错误的原因。你知道如何预防吗?
  • @Johnxr 您现在使用哪个版本的 prettier? 5 月份类似的issue 似乎已修复。请检查一下。
猜你喜欢
  • 2019-10-11
  • 2014-06-30
  • 1970-01-01
  • 1970-01-01
  • 2020-04-14
  • 2023-03-10
  • 2018-05-12
  • 1970-01-01
  • 2018-01-07
相关资源
最近更新 更多