[英]Strict Null Check Typescript Error on a JSX Element
I am creating a React component with Typescript which has a div JSX element with a 'style' attribute. 我正在用Typescript创建一个React组件,该脚本具有一个带有'style'属性的div JSX元素。 One of the values is background color, and I'm pulling that value from a Mobx State Tree, like this:
值之一是背景色,我正在从Mobx状态树中提取该值,如下所示:
style={{backgroundColor: css.primaryColor}}
However, this creates an error that the value might be undefined. 但是,这会导致错误,该值可能未定义。
Normally when calling from the Mobx tree in TS, I set the path equal to a variable, then add an if statement to satisfy this null check, like this: 通常,在TS中从Mobx树调用时,我将路径设置为变量,然后添加if语句来满足此空检查,如下所示:
const { store } = this.props
const currentBot = store.bots.current
if (currentBot) {
do something
}
So in the render function, I tried creating a variable called css, from which I can reference the different keys on the object (primaryColor in the above example). 因此,在render函数中,我尝试创建一个名为css的变量,从中可以引用对象上的不同键(上例中为primaryColor)。 This didn't work, because css could still be undefined, so I also tried adding an OR operator with a default hexcode.
这是行不通的,因为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'}}
/>
I'm still getting 'Object is possibly undefined' on the 'css' in the style attribute in VSCode. 我仍然在VSCode的style属性中的'css'上得到'Object is not undefined'。
How can I satisfy that null check? 我如何满足该空检查? Do I need to put the entire return statement inside of an if statement?
我是否需要将整个return语句放在if语句内?
If the intention is to just remove the error, add ! 如果只想消除错误,请添加! after the variable which you know is not null to quell this error.This tells the Typescript that the object is not null.
在您知道的变量不为null的变量之后以平息此错误。这告诉Typescript对象不为null。
eg 例如
<div
style={{backgroundColor: css!.primaryColor || '#707070'}}
/>
If you wish to learn how to use inline styles with Typescript, see the following links- 如果您想学习如何在Typescript中使用内联样式,请参见以下链接:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.