首页 > 解决方案 > 如何在 React 项目中扩展“CSSProperties”

问题描述

我来自javascript世界各地,对typescript. 我有一个用typescript. 我声明了一个内联样式,但在反应组件中使用它时收到以下警告:

Type '{ color: string; fontSize: string; fontWeight: number; }' is not assignable to type 'CSSProperties'.

下面是样式声明的代码。

const styles = {
    promAlert: {
        display: 'flex',
        flexDirection: 'column'
    }
};

下面是使用它的代码。这条线发出警告<div style={styles.promAlert}>

<div style={styles.promAlert}>
    {alert.substring('promotions.'.length)}
</div>

我已经搜索过这可能是由CSSPropertiesreact 中的定义引起的。我可能需要扩展这个类并在其上添加更多属性。我想知道如何在我的项目中做到这一点。

另一个问题是为什么CSSProperties不包括所有支持的 css 键。

标签: reactjstypescript

解决方案


TypeScript 需要特定的类型"flex""column",但没有任何额外的工作,它会同时接收string这两种类型,这太宽泛且无法描述。您可以在这里看到同样的错误:

declare const value: string
const a: "a" = value // errors, `string` can't be assigned to the more specific `"a"`

这里有一些解决方案。我认为最优雅的是as const,因此它将您的对象值视为其特定的文字类型。还要确保您的 TS 版本是最新的以使用它。

const styles = {
    promAlert: {
        display: 'flex',
        flexDirection: 'column',
    },
} as const

或者,您可以单独声明您的样式对象,并通过CSSProperties接口对它们进行类型检查。这会自动完成每个属性,但这不能(很容易)作为单个完整对象完成。

const promptAlert: React.CSSProperties = {
    display: 'flex',
    flexDirection: 'column'
}

// you can re-assign all of your styles into a single object if you want,
// but I think it would be easier to access `promptAlert` directly at this point
const styles = {
  promptAlert,
}

其他不太理想的解决方案:

  • { [key: string]: React.CSSProperties }:这不会对每个样式的名称进行类型检查,所以你可以做到styles.abcdef没有任何错误

  • 铸造每种风格as React.CSSProperties:这不会捕捉到风格本身的错误,例如你可能会错字display: "fleex"


推荐阅读