繁体   English   中英

JSX元素上的严格Null检查打字稿错误

[英]Strict Null Check Typescript Error on a JSX Element

我正在用Typescript创建一个React组件,该脚本具有一个带有'style'属性的div JSX元素。 值之一是背景色,我正在从Mobx状态树中提取该值,如下所示:

style={{backgroundColor: css.primaryColor}}

但是,这会导致错误,该值可能未定义。

通常,在TS中从Mobx树调用时,我将路径设置为变量,然后添加if语句来满足此空检查,如下所示:

const { store } = this.props
const currentBot = store.bots.current
if (currentBot) {
    do something
}

因此,在render函数中,我尝试创建一个名为css的变量,从中可以引用对象上的不同键(上例中为primaryColor)。 这是行不通的,因为css仍然可能是未定义的,所以我还尝试添加带有默认十六进制代码的OR运算符。

const { store } = this.props
const currentBot = store.bots.current
let css
if (currentBot) {
  css = currentBot.theme.css
}

...

<div
  style={{backgroundColor: css.primaryColor || '#707070'}}
/>

我仍然在VSCode的style属性中的'css'上得到'Object is not undefined'。

我如何满足该空检查? 我是否需要将整个return语句放在if语句内?

如果只想消除错误,请添加! 在您知道的变量不为null的变量之后以平息此错误。这告诉Typescript对象不为null。

例如

<div
  style={{backgroundColor: css!.primaryColor || '#707070'}}
/>

如果您想学习如何在Typescript中使用内联样式,请参见以下链接:

  1. https://medium.com/@zvona/react-native-and-typescript-meets-styles-b727ecf7e677
  2. https://blog.blueberry.io/how-we-handle-inline-styles-with-typescript-and-react-2c257e039f2b

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM