JSX 元素上的严格空检查 Typescript 错误

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
}

所以在渲染函数中,我尝试创建一个名为 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 中的样式属性 'css' 上得到 'Object is possibly undefined'。

我怎样才能满足空值检查?我需要将整个 return 语句放在 if 语句中吗?

如果只想删除错误,请添加 !在你知道的变量不为空之后平息这个 error.This 告诉 Typescript 该对象不为空。

例如

<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