当使用 React 的 props.children 使用 map 函数遍历时,可能会收到异常显示,原因是 props.children 是一个不可变的对象,不能直接对其数组进行 map 操作。解决方法是将 props.children 转换为数组,然后再进行 map 操作,例如使用 React.Children.toArray() 方法:
import React from 'react';
const ParentComponent = (props) => {
const childrenArray = React.Children.toArray(props.children);
return (
<div>
{childrenArray.map((child, index) => (
<div key={index}>{child}</div>
))}
</div>
);
};