Error with && logical operator jsx and typescript

只愿长相守 提交于 2021-02-11 12:36:35

问题


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:

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'.

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

回答1:


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>
      )}
    </>
  );


来源:https://stackoverflow.com/questions/63566207/error-with-logical-operator-jsx-and-typescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!