带有 TypeScript 的样式组件的“css”道具

Joh*_*ith 2 typescript styled-components

styled-components 有一个插件,允许以下内容:

<div
  css={`
    background: papayawhip;
    color: ${props => props.theme.colors.text};
  `}
/>
Run Code Online (Sandbox Code Playgroud)

有什么方法可以告诉我 TypeScriptcss是所有元素的有效属性吗?

for*_*d04 9

本期所述,将以下行添加到项目内的 TypeScript 文件中:

// e.g. src/global.d.ts

import {} from "styled-components/cssprop"
// or TS 3.8+
import type {} from "styled-components/cssprop"
Run Code Online (Sandbox Code Playgroud)

或者,您可以手动增加react模块类型声明 - 从"styled-components/cssprop"以上文件复制/粘贴内容:

import { CSSProp } from "styled-components"

interface MyTheme {} // declare custom theme type

declare module "react" {
  interface Attributes {
    css?: CSSProp<MyTheme>
  }
}
Run Code Online (Sandbox Code Playgroud)

后一种变体还允许您自定义css道具主题类型。

  • 替代解决方案对我有用。我在“styled.d.ts”中声明了这一点。谢谢 (2认同)