尽管代码可以正常工作,但typescript显示了以下问题:
Type '{ flexDirection: string; justifyContent: string; alignItems: string; marginLeft: string; minHeight: string; } | null' is not assignable to type 'CSSProperties | undefined'.
Type 'null' is not assignable to type 'CSSProperties | undefined'.ts(2322)
我想做的是灵活地改变一个基于布尔属性的元素的样式:
<nav style={refs.vertical === true ? verticalStyle : null} className={styles.navWrapper}>
和"verticalStyle"定义如下:
const verticalStyle = {flexDirection: 'column',
justifyContent:'space-evenly',
alignItems: 'flex-start',
marginLeft: '2rem',
minHeight: 'inherit'
}
既然代码运行得很好(并且在纯JS版本中这样做),我想知道为什么TS挣扎着认识到我实际上是在传递有效的CSS属性。除了使错误沉默,还有什么方法可以优雅地、无错误地解决这个问题吗?
不返回null
,而是返回空的object
或undefined
,因为Type是CSSProperties | undefined
。
<nav style={refs.vertical === true ? verticalStyle : {}} className={styles.navWrapper}>
或
<nav style={refs.vertical === true ? verticalStyle : undefined} className={styles.navWrapper}>
所以经过一番搜索,我终于找到了答案。基本上,在Typescript中不可能将样式作为变量传递。相反,样式必须直接内联应用。我不能找到确切的原因,但这是解决方案:
<nav style={refs.vertical === true ? {
flexDirection: 'column',
justifyContent: 'space-evenly',
alignItems: 'flex-start',
marginLeft: '2rem',
minHeight: 'inherit'
}
: undefined}