在Typescript中检测React子数组长度

IT技术 reactjs typescript
2021-05-01 02:16:38

我有一个可以接受 Reactchildren作为节点或节点数组的组件。我希望能够检测是否children是一个节点数组,但我收到以下 Typescript 错误:

TS2339:类型“字符串”上不存在属性“长度”| 数量 | 真实| {} | ReactElement<任何,字符串 | ((props: any) => ReactElement<any, any> | null) | (new (props: any) => Component<any, any, any>)> | ... 47 更多... | (ReactNode[] & ReactPortal)'。'number' 类型不存在属性 'length'。

typescript中有没有办法检测children长度?谢谢。

import React from 'react';

interface Props {
  children: React.ReactNode | React.ReactNode[];
}

const SampleComponent: React.FC<Props> = ({ children }) => {
  if (children && children.length) {
    return children.map((child) => (
      <div>{child}</div>
    ));
  }

  return children;
};

export default SampleComponent;

在此处输入图片说明

3个回答

有一个React.ChildrenAPI 用于处理props.children(这是一个不透明的数据结构)。

此外,React.Children还有countmap方法

if (React.Children.count(children)) {
  return React.Children.map(children, (child) => <div>{ ..todo.. }</div>)
}

它也有 TypeScript 支持。因此,您不需要强制转换类型。

[更新]

使用 React.Children API查看Ajeet Shah 的响应

[原来的]

在像这样检查长度之前将孩子们投射到 React.ReactNode[] :

(children as React.ReactNode[]).length

您还可以创建一个类型谓词:

https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates

在这种情况下最好的方法是不使用 Reacf.FC

定义 props likeconst MyButton = (props: MyProps)=>... 或者使用React.VFC

函数组件 - 为什么React.FC不鼓励?

在此处输入图片说明