【问题标题】:CSS Emotion Library - Getting css props error when using css propCSS 情感库 - 使用 css 道具时出现 css 道具错误
【发布时间】:2020-08-27 15:58:15
【问题描述】:

这是我的代码

import { css, jsx } from '@emotion/core'
       
return (
       <>
       <img css={css`height: 200px; height: 200px;`} fluid={image.sharp.fluid} />
       <List>
           <li>Our Clients</li>
           <li>What We Do</li>
           <li>Contact</li>
       </List>
       </>
   )

这是我遇到的错误

您已尝试对从css 函数返回的对象进行字符串化。它 不应该直接使用(例如作为 className 的值 道具),而是交给情感,以便它可以处理它(例如,作为价值 css 道具)。

这个错误似乎告诉我我需要做我已经在做的事情?还是我在这里遗漏了什么。

【问题讨论】:

  • 你能分享你的.babelrc吗?

标签: css reactjs emotion


【解决方案1】:

除了包含 @emotion/babel-plugin 之外,还有一些我错过的配置导致了该错误。

{
  "presets": [
    [
      "@babel/preset-react",
      { "runtime": "automatic", "importSource": "@emotion/react" }
    ]
  ],
  "plugins": ["@emotion/babel-plugin"]
}

"importSource": "@emotion/react" 丢失。添加后,错误消失,样式实现correc5y。

【讨论】:

    【解决方案2】:

    作为 detailed in the Emotion documentation,使用 css 属性需要将 React 替换为 jsx 作为 JSX 元素的目标函数(称为“pragma”),这将使 Emotion 能够拦截 @987654329 @prop 并将其转换为 className React 的 prop。

    例如:

    <p>Hi</p>
    
    // Becomes the following by default:
    React.createElement("p", {}, "Hi")
    
    // But with the `jsx` pragma, it becomes:
    jsx("p", {}, "Hi")
    

    有两种概述的方法可以实现这一目标。你只需要选择一个。如果你能够在你的应用程序中配置 Babel,第一个是推荐的方法,但是任何一个都可以正常工作:

    1. Install a Babel pluginjsx 配置为应用中所有代码的默认处理程序

      最直接的方法是将相关的 Babel 预设添加到您的 Babel 配置中,如下所示:

      // Option 1A — Good
      // Add @emotion/babel-preset-css-prop to your dev dependencies, then
      // add the preset to your .babelrc configuration:
      
      {
        "presets": ["@emotion/babel-preset-css-prop"]
      }
      

      不过,如果您能够做到这一点,我建议您改为配置 babel-plugin-emotion,其中包括 css 属性配置以及其他功能,如缩小、死代码消除和提升:

      // Option 1B — Better
      // Add babel-plugin-emotion to your dev dependencies, then add
      // the plugin to your Babel configuration (e.g. .babelrc)
      {
        "plugins": ["emotion"]
      }
      
    2. 从 Emotion 中导入 jsx 函数并指示 Babel 使用这个导入的函数 on a per-file basis using pragma

      /** @jsx jsx */
      import { jsx } from '@emotion/core'
      

    【讨论】:

    【解决方案3】:

    只是想说明我遇到了这个问题并添加它为我修复了错误:

    /** @jsx jsx */
    import { jsx } from '@emotion/core';
    

    为了澄清,您必须在文件顶部添加/** @jsx jsx */;

    【讨论】:

    • 谢谢。我认为这也应该在情感文档中突出显示
    • 这在现在的 Typescript 部分下的情感文档中突出显示。请注意,它会阻止您使用 > 速记。你仍然可以使用 Fragment emotion.sh/docs/typescript
    【解决方案4】:

    /**@jsx jsx */ 从 '@emotion/core' 导入 { jsx, css }

    【讨论】:

    • 欢迎来到 Stack Overflow。 Stack Overflow 上不鼓励仅使用代码的答案,因为它们没有解释它是如何解决问题的。请编辑您的答案以解释代码的作用以及它如何回答问题,以便它对其他有类似问题的用户以及 OP 也有用。另外,请正确格式化您的代码。
    【解决方案5】:

    你需要安装这个 babel 插件,babel-preset-css-prop

    【讨论】:

      猜你喜欢
      • 2022-10-20
      • 2021-06-19
      • 2022-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-14
      相关资源
      最近更新 更多