首页 > 解决方案 > Gatsby Styled Components , CSS 显示在

问题描述

我正在构建一个带有样式组件的 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 显示在<head>标签中。在下图中,您可以看到左上角显示的 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"
  }
}

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

标签: gatsbystyled-components

解决方案


我以前从未使用过 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;

应该有效。您可能总是想为 设置一个更具体的常数<h1>


推荐阅读