我的应用程序中出现以下错误(npm 5.4.2、react 15.4、typescript 2.5.3、webpack 2.2.1、webpack-dev-server 2.4.1)。
这会起作用:
<div style={{position: 'absolute'}}>working</div>
这不会编译:
const mystyle = {
position: 'absolute'
}
<div style={mystyle}>not working</div>
编译错误为:
ERROR in ./src/components/Resource.tsx
(61,18): error TS2322: Type '{ style: { position: string; }; children: string; }' is not assignable to type 'DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>'.
Type '{ style: { position: string; }; children: string; }' is not assignable to type 'HTMLAttributes<HTMLDivElement>'.
Types of property 'style' are incompatible.
Type '{ position: string; }' is not assignable to type 'CSSProperties'.
Types of property 'position' are incompatible.
Type 'string' is not assignable to type '"inherit" | "initial" | "unset" | "fixed" | "absolute" | "static" | "relative" | "sticky"'.
webpack: Failed to compile.
但是有什么区别呢? 我可以用以下方法修复它:
const mystyle = {
position: 'absolute' as 'absolute'
}
但这是一个好的解决方案吗?
我对其他样式/CSS 属性没有这个问题。
我在github上发现了类似的问题: https://github.com/Microsoft/TypeScript/issues/11465 但如果理解正确的话,这是早期版本中的打字稿错误。
任何帮助表示赞赏。
这是一个解决方法,但没关系。 其他一些解决方案是:
const mystyles = {
position: 'absolute',
} as React.CSSProperties;
您可以回来查看此问题何时得到解决。从里程碑来看,我猜大约是 TS 2.6。
使用 React.CSSProperties 类型:
import React, { CSSProperties } from "react";
const myStyles: CSSProperties = {
position: 'absolute',
}
然后照常使用样式即可:
<div style={myStyles} />
您可以使用 const 断言让 TypeScript 推断整个对象的文字值:
const mystyle = {
position: 'absolute'
} as const;
这样,如果您向
mystyle
添加更多属性,它也适用于它们。
如果您有嵌套样式对象,superluminary的答案将不起作用。在这种情况下,您可以创建一个类型:
import React, { CSSProperties } from 'react';
export interface StylesDictionary{
[Key: string]: CSSProperties;
}
并像这样使用它:
const styles:StylesDictionary = {
someStyle:{
display:'flex',
justifyContent:'center',
},
someOtherStyle:{
display:'flex',
justifyContent:'center',
alignItems:'center',
}
}
然后:
<div style={styles.someStyle} />
我在尝试将wrapperHeight字符串值(100px、10vw、100vh等)传递给HeroImage组件时遇到了类似的问题。解决方案是在 CSS 对象内的值周围实际使用字符串文字(拗口):
interface HeroImageProps {
src: StaticImageData,
alt: string,
wrapperHeight: string,
}
export default function HeroImage({ src, alt, wrapperHeight }: HeroImageProps) {
const wrapperStyles: React.CSSProperties = {
height: `${wrapperHeight}`
}
return (
<div className={styles.heroImage} style={wrapperStyles} >
<Image
src={src}
alt={alt}
layout="fill"
priority
/>
</div>
)
}
satisfies
运算符:
const styles = {
position: 'absolute',
} satisfies React.CSSProperties