要遍历 React Children 的嵌套子元素,可以使用 React.Children API 中的 React.Children.map() 方法。该方法能够遍历给定 React.children 数据类型(例如:React元素或者数组)的每一个子元素,并返回一个包含每个子元素处理后的结果的新数组。
例如,在以下代码中,我们想遍历一个包含了嵌套子元素的list对象,然后将每个三级子元素中的name属性打印出来:
import React from 'react';
const list = (
-
level 1
-
level 2
- name: Alice
- name: Bob
);
const flattenList = (children) =>{
return React.Children.toArray(children).reduce((acc, child) => {
return acc.concat(
child.props.children ? flattenList(child.props.children) : child
);
}, []);
};
const renderListItemNames = () =>{
const items = flattenList(list);
items.forEach((item) =>{
if (typeof item === 'object' && item.props && item.props.name) {
console.log(`name: ${item.props.name}`);
}
});
};
renderListItemNames();
在示例代码中,我们重写了一个flattenList(children)函数,该函数能够遍历list里的每一个嵌套元素,并通过reduce方法将其传递给一个新的数组acc。我们再使用React.Children API将列表实例转换为一个数组,并且遍历新的扁平化数组以找到属性中含有name的元素,并将其打印出来。
输出结果应为以下内容:
name: Alice
name: Bob
通过以上代码,我们可以轻松地遍历React Children的嵌套子元素。