问题:在使用children过程中发现children不包含map方法,但是类型验证表明children就是array类型
解决:
1、由于在props中写明children时一个React.ReactNode类型(此类型代表children可以是任何类型),所以即使类型检查为array类型,在使用children.map()的时候认为children依旧时全类型,不包含map方法。
2、这里使用React.Children.map将children转化为固定array类型,也就包含了map方法。
案例:
父组件使用:
children?: React.ReactNode;
render(){
const { children} = this.props;
return React.Children.map(children, (child: any, index) => {
console.log(child)
return (
<div>
{child}
</div>
);
});
}