&&错误逻辑运算符jsx和打字稿

问题描述:

我对打字稿很陌生,我想知道为什么这样做失败

I'm fair new to typescript and I was wondering why this fails

import {CircularProgress} from 'components/shared/material'

import React from 'react'

import loadingStyles from './styles'

const Loading = ({active}: {active: boolean}) => {
 const classes = loadingStyles({active, fadeSpeed: 1})
 return (
  active && (
   <div className={classes.overlay}>
    <CircularProgress />
   </div>
  )
 )
}

export default Loading

当我尝试在其他组件中使用它时,会显示以下消息:

And when I try to use it in another component I get this message:

正在加载"不能用作JSX组件. 其返回类型为'false |元素"不是有效的JSX元素. 类型'false'不能分配给类型'Element |空".

Loading' cannot be used as a JSX component. Its return type 'false | Element' is not a valid JSX element. Type 'false' is not assignable to type 'Element | null'.

这很奇怪,因为它将与常规js一起使用,并且在typescript中,仅当我使用像这样的三元语句时才起作用:

It is strange because that will work with regular js and here in typescript only works if I use a ternary statement like this one:

  return active ? (
   <div className={classes.overlay}>
    <CircularProgress />
   </div>
  ) : null

如果您真的想使用简写-您可以执行此操作.使用<</>允许多行(在这种情况下为可选),并确保单元素在函数上返回.并且将条件代码包装在{}周围,将确保您可以添加任意数量的&&&在其中进行检查以呈现您的组件.

If you really want to use a shorthand - you can do this. Use of <></> allows multi-line (optional in this case) and ensures the single element return on the function. And wrapping your conditional code around {} will ensure you can add any number of && checks within this to render your component.

  return (
    <>
      {active && (
        <div className={classes.overlay}>
          <CircularProgress />
        </div>
      )}
    </>
  );