【问题标题】:Type 'boolean' is not assignable to type 'ReactElement<any, any>'类型 \'boolean\' 不可分配给类型 \'ReactElement<any, any>\'
【发布时间】:2022-08-04 01:19:59
【问题描述】:

请有人解释如何修复 TS 抛出的错误:类型 \'boolean\' 不可分配给类型 \'ReactElement<any, any>\'。在我的代码中,我想根据isCorrect 值显示&lt;Confetti/&gt; 组件。如果 var 具有虚假值,我不需要渲染。如何正确地制作这种类型的逻辑?

import React, { FC } from \'react\'
import ReactConfetti from \'react-confetti\';
import { useWindowSize } from \'react-use\';

interface ConfettiProps {
    isCorrect: boolean;
}

interface WindowDimensions {
    width: number;
    height: number;
  }

const Confetti: FC<ConfettiProps> = ({isCorrect}) => {
    const { width, height }: WindowDimensions = useWindowSize();

  return (
    isCorrect && (<ReactConfetti width={width} height={height}/> )
  )
}

export default Confetti; 
  • 我认为您不能只在 JSX 元素或布尔值上不返回任何内容。我猜那是正确的? <ReactConfetti> : null 会起作用。
  • @Pelicer 谢谢,它有效)

标签: reactjs typescript


【解决方案1】:

两种选择:

return (
  isCorrect ? (<ReactConfetti width={width} height={height}/> ) : null
)
return (
  <>isCorrect && (<ReactConfetti width={width} height={height}/> )</>
)

&lt;&gt;&lt;/&gt; 是一个反应片段

【讨论】:

    猜你喜欢
    • 2018-12-09
    • 1970-01-01
    • 1970-01-01
    • 2022-12-13
    • 2017-08-12
    • 1970-01-01
    • 2021-04-22
    • 2018-08-14
    • 2021-12-10
    相关资源
    最近更新 更多