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
| 归档时间: |
|
| 查看次数: |
6366 次 |
| 最近记录: |