【问题标题】:How to conditional render a compnent in react + typescript如何在 react + typescript 中有条件地渲染组件
【发布时间】:2020-05-27 15:02:08
【问题描述】:

更新

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

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 />

当我在打字稿中尝试时得到错误:

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

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

【问题讨论】:

  • 通常情况下,孩子们是假的完全没问题。该父组件对其道具有什么类型定义(我认为该组件是“LesserContentColumn”)?它可能对类型的限制超出了应有的范围

标签: javascript reactjs typescript ecmascript-6


【解决方案1】:

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

现在它不抱怨了:

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

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

【讨论】:

    【解决方案2】:

    尝试使用三元运算符,这样你要么使用组件,要么使用 null:

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

    【讨论】:

    • 现在显示为 null |元素。真相应该隐藏在我声明组件的方式中,我会更新我的问题。谢谢。
    • 如果删除这些行,错误会消失吗?由于类声明中的另一个问题,我遇到了打字稿错误识别问题的情况
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-22
    • 2018-12-20
    • 1970-01-01
    • 2015-05-16
    • 1970-01-01
    • 2020-06-23
    • 2021-12-17
    相关资源
    最近更新 更多