【问题标题】:Gatsby Styled Components , CSS is displaying in <head>Gatsby Styled Components , CSS 显示在 <head>
【发布时间】:2021-04-04 13:26:43
【问题描述】:

我正在构建一个带有样式组件的 Gatsby 网站。

这是我的问题。当我使用这样的样式组件创建组件时:

import React from 'react'
import styled from 'styled-components'

const Test = () => {
    return (
        <Wrapper>
            <h1>Test</h1>
        </Wrapper>
    )
}

export default Test

const Wrapper = styled.section`
h1 {
    font-size: 300px;
}
`

结果: CSS 显示在 &lt;head&gt; 标记中。在下图中,您可以看到 CSS 显示在左上角。

我正在使用最新版本的 Gatsby,我的 package.json 看起来像这样

{
  "name": "gatsby-starter-hello-world",
  "private": true,
  "description": "A simplified bare-bones starter for Gatsby",
  "version": "0.1.0",
  "license": "0BSD",
  "scripts": {
    "build": "gatsby build",
    "develop": "gatsby develop",
    "format": "prettier --write \"**/*.{js,jsx,ts,tsx,json,md}\"",
    "start": "npm run develop",
    "serve": "gatsby serve",
    "clean": "gatsby clean",
    "test": "echo \"Write tests! -> https://gatsby.dev/unit-testing\" && exit 1"
  },
  "dependencies": {
    "@fortawesome/fontawesome-svg-core": "^1.2.32",
    "@fortawesome/free-solid-svg-icons": "^5.15.1",
    "@fortawesome/react-fontawesome": "^0.1.13",
    "gatsby": "^2.29.2",
    "gatsby-image": "^2.8.0",
    "gatsby-plugin-react-helmet": "^3.7.0",
    "gatsby-plugin-sharp": "^2.11.2",
    "gatsby-transformer-sharp": "^2.9.0",
    "react": "^16.14.0",
    "react-dom": "^16.14.0",
    "react-helmet": "^6.1.0",
    "react-icons": "^4.1.0",
    "styled-components": "^5.2.1"
  },
  "devDependencies": {
    "prettier": "2.2.1"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/gatsbyjs/gatsby-starter-hello-world"
  },
  "bugs": {
    "url": "https://github.com/gatsbyjs/gatsby/issues"
  }
}

我在 Google 上没有找到任何与此问题相关的内容。以前有人遇到过同样的问题吗?您需要查看其他代码吗?希望有人能帮忙。

【问题讨论】:

    标签: gatsby styled-components


    【解决方案1】:

    我以前从未使用过 Gatsby,但 AFAIK 可能取决于常量的顺序(cfr.https://www.gatsbyjs.com/docs/how-to/styling/styled-components/)。试试这个:

    import React from "react";
    import styled, { css } from "styled-components";
    
    const Wrapper = styled.section`
        h1 {
            font-size: 300px;
        }
    `;
    
    const Test = () => {
        return (
            <Wrapper>
              <h1>Test</h1>
            </Wrapper>
        )
    }
    
    export default Test;
    

    应该工作。您可能总是希望为&lt;h1&gt; 设置一个更具体的常量。

    【讨论】:

    • 我试过你的方法,但它不起作用。超级奇怪的错误哈哈。
    猜你喜欢
    • 2018-10-13
    • 2021-04-06
    • 2022-08-06
    • 2018-07-14
    • 2021-06-27
    • 2021-02-19
    • 2021-02-26
    • 2023-03-24
    • 1970-01-01
    相关资源
    最近更新 更多