【问题标题】:React/TypeScript - Type 'false | Element' is not assignable to type 'Element'React/TypeScript - 类型 'false |元素'不可分配给类型'元素'
【发布时间】:2021-02-24 08:53:13
【问题描述】:

我收到此错误:键入 'false | Element' 不可分配给类型 'Element'。

我正在使用 React 和 TypeScript,代码如下:

function App() {
    const [isSearching, setIsSearching] = useState(false);
    return (
        {isSearching && <div> Hey </div>}
    )
}

{isSearching &amp;&amp; &lt;div&gt; Hey &lt;/div&gt;} 出现上述错误

谁能帮我指出我在这里可能遗漏了什么?

【问题讨论】:

    标签: javascript reactjs typescript react-hooks


    【解决方案1】:

    React 组件应该返回一个 JSX。如果 isSearching 为 false,则返回 false 并且没有 JSX。

    这应该可以解决问题:

    function App() {
        const [isSearching, setIsSearching] = useState(false);
        return (
            <>
              {isSearching && <div> Hey </div>}
            </>
        )
    }
    

    【讨论】:

      【解决方案2】:

      你一定忘记在你的组件中返回一个值。

      function App() {
          const [isSearching, setIsSearching] = useState(false);
      
          return isSearching ? (<div> Hey </div>) : null
      }
      

      【讨论】:

      • 还是同样的问题。现在错误是Type 'Element | null' is not assignable to type 'Element'. Type 'null' is not assignable to type 'Element'.ts(2322)
      猜你喜欢
      • 2023-03-30
      • 2020-07-04
      • 2021-12-06
      • 1970-01-01
      • 1970-01-01
      • 2021-07-29
      • 2020-03-08
      • 1970-01-01
      • 2022-08-23
      相关资源
      最近更新 更多