【问题标题】:Strict Null Check Typescript Error on a JSX ElementJSX 元素上的严格空值检查 Typescript 错误
【发布时间】:2019-01-16 00:22:34
【问题描述】:

我正在使用 Typescript 创建一个 React 组件,它有一个 div JSX 元素和一个 'style' 属性。其中一个值是背景颜色,我从 Mobx 状态树中提取该值,如下所示:

style={{backgroundColor: css.primaryColor}}

但是,这会产生一个错误,即该值可能未定义。

通常在TS中从Mobx树调用时,我将路径设置为一个变量,然后添加一个if语句来满足这个null检查,像这样:

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”上得到“对象可能未定义”。

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

【问题讨论】:

    标签: reactjs typescript jsx mobx mobx-react


    【解决方案1】:

    如果只是为了消除错误,请添加 !在你知道不为空的变量之后消除此错误。这告诉 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

    【讨论】:

    • 谢谢,我去看看链接!
    猜你喜欢
    • 2017-09-01
    • 2019-03-23
    • 2020-04-05
    • 2017-03-12
    • 1970-01-01
    • 2016-12-07
    • 2019-07-21
    • 2018-10-04
    • 1970-01-01
    相关资源
    最近更新 更多