【问题标题】:React typescript and children反应打字稿和孩子
【发布时间】:2023-04-06 21:29:01
【问题描述】:

我尝试在打字稿中动态检查反应子组件的类型。 以下代码运行良好,但似乎 typescript 不希望我解构孩子。

我收到打字稿错误:

TS2339: Property 'type' does not exist on type 'ReactNode'.

除了使用 // @ts-ignore 之外,我能做些什么来摆脱打字稿错误。

import * as React from 'react';

    export interface AuxProps  { 
      children: React.ReactNode[]
    }

    export const Message: React.FC<AuxProps> = ({
      children,
    }: AuxProps) => {
      
      const test = children.filter(({ type }) => type === Test);

      return (
        <div>
          {test}
        <div/>
      );
    };

【问题讨论】:

    标签: reactjs typescript children


    【解决方案1】:

    您无法从ReactChild 中读取type,因为ReactChild 是一个联合,并且并非该联合的每个成员都有一个名为type 的属性。

    事实上,只有ReactElements 可以。

    解决方案是检查谓词函数中的两件事:

    • 这个孩子是ReactElement吗?
    • 如果是,那么该元素是所需类型吗?

    代码:

    const test = children.filter(child => React.isValidElement(child) && child.type === 'Test');
    

    【讨论】:

      【解决方案2】:

      这是因为默认的ReactNode 没有字段类型。

      您可以使用 & 功能简单地添加该键:

      export interface AuxProps  { 
            children: (React.ReactNode & {type: string})[]
          }
      
      

      这会将type 添加到元素中。

      【讨论】:

      • 是的,谢谢,但还有一个问题。如果我检查:type ReactNode = ReactChild | ReactFragment | ReactPortal | boolean | null | undefined;type ReactChild = ReactElement | ReactText; interface ReactElement&lt;P = any, T extends string | JSXElementConstructor&lt;any&gt; = string | JSXElementConstructor&lt;any&gt;&gt; { type: T; props: P; key: Key | null; } 那么实际上它应该已经存在了吗?
      • 太好了,如果能解决您的问题,您能否接受答案。这是因为它可能是两者,只有第二个有类型,而不是第一个。所以只有一半有它,而且它可以是,节点没有它。如果你使用 ReactChild insteda,那应该可以工作
      猜你喜欢
      • 2021-11-18
      • 1970-01-01
      • 2020-10-24
      • 2019-07-11
      • 2018-09-29
      • 2023-03-29
      • 2017-09-26
      • 2022-01-12
      • 1970-01-01
      相关资源
      最近更新 更多