我来自javascript
世界和新手 typescript
.我有一个用 typescript
编写的 React 项目.我声明了一个内联样式,但在 React 组件中使用它时收到以下警告:
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>
我搜索过这可能是由CSSProperties
引起的在 react 中定义。我可能需要扩展此类并在其上添加更多属性。我想知道如何在我的项目中做到这一点。
另一个问题是为什么CSSProperties
不包括所有受支持的 css 键。
最佳答案
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
接口(interface)进行类型检查。这为每个属性提供了自动完成功能,但这不能(轻松地)作为一个完整的对象来完成。
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
没有任何错误将每个样式
转换为 React.CSSProperties
:这不会捕获样式本身的错误,例如你可能打错了display: "fleex"
关于reactjs - 如何在 React 项目中扩展 `CSSProperties`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50960084/