如何在 React + TypeScript 中条件渲染组件

The*_*ris 1 javascript typescript ecmascript-6 reactjs

更新

也许解决方案在于我声明组件的方式:

import React, { FunctionComponent } from 'react';

export const ChapterDescription: FunctionComponent<
    ChapterDescription
   > = (
   {
    description,
    name,
   }: ChapterDescription,
   ) => (
   <div>
     <h3>{name}</h3>
     <p>{description}</p>
   </div>
 );
Run Code Online (Sandbox Code Playgroud)

当我仅用于reactjs我的组件时,我可以轻松地有条件地渲染组件,如下所示(检查chapters数组是否有项目,然后渲染组件):

<OtherComponent/>    
    <div>
        {chapters.length > 0 && <ChapterDescription
            name={name}
            description={description}
        />}
    </div>
<OtherComponent2 />
Run Code Online (Sandbox Code Playgroud)

当我在打字稿中尝试时,出现错误:

Type 'false | Element' is not assignable to type 'Element'.
  Type 'false' is not assignable to type 'Element'.ts(2322)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

条件渲染不再是不好的做法了吗?我该如何处理这个案子?

The*_*ris 11

好吧,这不是那么明显,但片段是打字稿中条件渲染的解决方案解决方案之一:

现在它不再抱怨:

<Acomponent />
 <>
   {chapters && chapters.length > 0 && (
     <ChapterDescription
       name={selectedChapter.name}
       description={selectedChapter.description}
     />
   )}
 </>
<AnotherComponent />
Run Code Online (Sandbox Code Playgroud)

来源: https: //en.reactjs.org/docs/fragments.html