[英]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 />
尝试使用三元运算符,这样您可以使用组件或 null:
<OtherComponent/>
<div>
{chapters.length > 0 ? <ChapterDescription
name={name}
description={description}
/> : null}
</div>
<OtherComponent2 />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.