问题
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