在Gatsby.js中使用Emotion的问题

时间:2020-05-31 00:39:09

标签: javascript css reactjs gatsby emotion

我正在关注有关使用情感的盖茨比教程。 https://www.gatsbyjs.org/docs/recipes/styling-css#using-emotion

我使用npm install --save gatsby-plugin-emotion @emotion/core @emotion/styled安装了Emotion,并像这样设置了gatsby-config.js文件


module.exports = {
  plugins: [`gatsby-plugin-emotion`],
}

但是当我像本教程一样使用它时,遇到一个问题,其中组件的内联css是[object Object]

我的组件看起来像这样

import React from "react"
import { css } from "@emotion/core"

export default ({ children }) => (
  <main
    css={{
      backgroundColor: "red",
    }}
  >
    {children}
  </main>
)

我试图用另一种方法重写

import React from "react"
import { css } from "@emotion/core"

export default ({ children }) => (
  <main
    css={css`
      background-color: red;
    `}
  >
    {children}
  </main>
)

这次组件的inline-css是一个段落

You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop). 

不知道为什么这两种方法不起作用

1 个答案:

答案 0 :(得分:0)

这对我有用(没有充分的了解):

方法01

替换此:

import React from "react"
import { css } from "@emotion/core"

与此:

/** @jsx jsx */
import { css, jsx } from "@emotion/core"

方法02

更新gatsby-config.js以包含插件gatsby-plugin-emotion

module.exports = {
  plugins: [
    `gatsby-plugin-emotion`,
  ],
}

这需要重新启动gatsby开发过程。