reactjs - 错误 TS2322 : Property 'css' does not exist on type 'DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>'

标签 reactjs typescript styled-components

我最近决定将我的代码库从 JS 迁移到 TS 以添加类型检查。我还使用了 styled-components 库。

但是,我遇到了以下问题:

error TS2322: Type '{ children: string; css: string; }' is not assignable to type 'DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>'.
  Property 'css' does not exist on type 'DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>'.

这是一个基本的代码示例:

import React from 'react'
const MyComponent: React.FC = (props) => {
    return (
        <div css={`
            padding: 44px;
        `}>
            My content
        </div>
    )
}

请注意我的 tsconfig.json compilerOptions 看起来像这样:

"compilerOptions": {
        "composite": true,
        "declaration": true,
        "outDir": "./dist", // https://www.typescriptlang.org/tsconfig#outFile
        "rootDir": "./src",
        "jsx":"react",
        "types": ["@types/styled-components"],
        "module": "commonjs",
        "target": "es5",
        "sourceMap": true,
        
        "declarationMap": true,
        "noEmitOnError": true,
        "skipLibCheck": true,
        "esModuleInterop": true,
        "noUnusedLocals":true,
        "noUnusedParameters":true,
        "allowJs":true,
        "noEmit": false
    }

任何人都可以指出正确的方向来解决 css 属性的类型吗?

最佳答案

使用以下代码创建 styledComponentsOverride.d.ts:

import { CSSProp } from 'styled-components'

interface MyTheme {}

declare module 'react' {
    interface Attributes {
       css?: CSSProp<MyTheme>
    }
}

这将使用可选的 CSS 属性扩展 react 元素属性类型

更多信息:https://github.com/DefinitelyTyped/DefinitelyTyped/issues/31245

关于reactjs - 错误 TS2322 : Property 'css' does not exist on type 'DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70127482/

相关文章:

html - 对齐文本和微调器垂直居中

javascript - SignUp 和 SignIn 组件之间的路由

reactjs - 如何从'office-ui-fabric-react导入自动绑定(bind)?

reactjs - 当我从样式组件使用我自己的库时出现无效的钩子(Hook)调用错误

javascript - 过渡CSS属性使内容看到两次

javascript - 从 Typescript 中的基类创建子类的新实例

javascript - NestJS/TypeORM : Cannot set property metadata of#<Repository> which has only a getter

Angular 6 - textarea(更改)永远不会更改 textarea 的内容

reactjs - React Hooks useState 事件处理程序与样式组件

css - 使用 styled-components 动画背景渐变