在 Typescript 中检测 React 子数组长度

Jim*_*mmy 9 typescript reactjs

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

\n
\n

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

\n
\n

Typescript 有没有办法检测是否children有长度?谢谢。

\n
import React from \'react\';\n\ninterface Props {\n  children: React.ReactNode | React.ReactNode[];\n}\n\nconst SampleComponent: React.FC<Props> = ({ children }) => {\n  if (children && children.length) {\n    return children.map((child) => (\n      <div>{child}</div>\n    ));\n  }\n\n  return children;\n};\n\nexport default SampleComponent;\n
Run Code Online (Sandbox Code Playgroud)\n

在此输入图像描述

\n

Aje*_*hah 14

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

此外,React.Children还有countmap等方法。

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

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