我有一个可以接受 React 的组件children
作为节点或节点数组。我希望能够检测到是否children
是一个节点数组,但我收到以下 Typescript 错误:
TS2339:类型“string |”上不存在属性“length”数量 |真实 | {} | ReactElement ReactElement | null) | (new (props:any) => Component)> | ... 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;
有一个React.Children https://reactjs.org/docs/react-api.html#reactchildrenAPI 用于处理props.children
(这是一个不透明的数据结构).
Also, React.Children
有类似的方法count https://reactjs.org/docs/react-api.html#reactchildrencount, map https://reactjs.org/docs/react-api.html#reactchildrenmap etc.
if (React.Children.count(children)) {
return React.Children.map(children, (child) => <div>{ ..todo.. }</div>)
}
它也有 TypeScript 支持。因此,您不需要强制转换类型。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)