【问题标题】:emotion with react 18 and typescriptReact 18 和打字稿的情感
【发布时间】:2022-07-05 02:19:17
【问题描述】:

当我尝试将 create-react-app 与 react 18、typescript 和emotion 11 一起使用时,css 属性不起作用——元素仍处于样式化状态,并且在 DOM 中,该元素具有 css 属性,其值是:

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

我可以通过建立一个新项目来重现:

npx create-react-app test-ts-emotion --template typescript
cd test-ts-emotion 
npm i --save @emotion/react

然后我将src/App.tsx 编辑为:

import React from 'react';
import { css } from '@emotion/react';

function App() {
  return (
    <div css={css`background-color: red`}>
      Hello, tester.
    </div>
  );
}

export default App;

然后我将jsxImportSource 添加到tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx",
    "jsxImportSource": "@emotion/react"
  },
  "include": [
    "src"
  ]
}

尽管如此,css 属性不起作用(该元素没有样式,我将上述消息作为 DOM 属性的值):

您可以在my test repo on Github 上查看此设置。我相信我已经关注了the instructions,但也许我错过了一些东西。提前致谢!

【问题讨论】:

标签: reactjs typescript emotion react-18


【解决方案1】:

如果您像我一样使用create-react-app,则必须在每个文件的顶部添加显式配置:

/** @jsxImportSource @emotion/react */

this Emotion issue 中引用并确认了此解决方案。这最终是一个create-react-app 错误。 this pull request on create-react-app 中有一个修复程序,但它是在一年多前提交的,Facebook 上没有人费心查看它,所以我怀疑它是否会被合并。

【讨论】:

    猜你喜欢
    • 2021-06-19
    • 1970-01-01
    • 2019-04-24
    • 2013-12-29
    • 1970-01-01
    • 1970-01-01
    • 2023-01-27
    • 2020-02-08
    • 2018-03-18
    相关资源
    最近更新 更多