reactjs - 如何在 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>
我已经搜索过这可能是由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
接口对它们进行类型检查。这会自动完成每个属性,但这不能(很容易)作为单个完整对象完成。
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"
推荐阅读
- c# - 将 dataGridView 重新启动为空状态
- python-3.x - ticker.FuncFormatter 不应用刻度标签,为什么?
- docker - 无法在 Kubernetes 的不同节点上卷曲 pod
- methods - 如何将对 self 的可变引用转换为不可变引用以用作方法的参数?
- angular - 不显示异步的自定义管道
- javascript - 在视图加载时展开 ngx-datatable
- xml - 如何让 XMLLINT 将 --xpath 结果作为数组
- javascript - Intl.Collator 排序日文 - 为什么整理器不优先考虑日文字符?
- javascript - 在数组上分配 nr
- sql - 比较hive表时如何计算记录的百分比?