繁体   English   中英

如何在反应 + typescript 中有条件地渲染组件

[英]How to conditional render a compnent in react + typescript

更新

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

import React, { FunctionComponent } from 'react';

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

当我只为我的组件使用reactjs时,我可以轻松地像这样有条件地渲染组件(检查chapters数组是否有项目,然后渲染组件):

<OtherComponent/>    
    <div>
        {chapters.length > 0 && <ChapterDescription
            name={name}
            description={description}
        />}
    </div>
<OtherComponent2 />

当我在 typescript 中尝试时得到错误:

Type 'false | Element' is not assignable to type 'Element'.
  Type 'false' is not assignable to type 'Element'.ts(2322)

在此处输入图像描述

再有条件渲染是不好的做法吗? 我该如何处理这种情况?

那么它不是那么明显,但片段是typescript 中条件渲染的解决方案解决方案之一:

现在它没有抱怨:

<Acomponent />
 <>
   {chapters && chapters.length > 0 && (
     <ChapterDescription
       name={selectedChapter.name}
       description={selectedChapter.description}
     />
   )}
 </>
<AnotherComponent />

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

尝试使用三元运算符,这样您可以使用组件或 null:

<OtherComponent/>    
    <div>
        {chapters.length > 0 ? <ChapterDescription
            name={name}
            description={description}
        /> : null}
    </div>
<OtherComponent2 />

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM