使用场景:
-
需要对子组件进行统一处理(如添加
key、包裹额外元素、过滤特定类型等)。 -
动态修改
children的 props 或结构。
示例代码:遍历并修改 children
import React from 'react';
// 一个组件,给每个子项添加边框和序号
const ListWithIndices: React.FC = ({ children }) => {
return (
<div>
{React.Children.map(children, (child, index) => {
// 检查是否是有效的 React 元素(避免处理字符串、数字等)
if (React.isValidElement(child)) {
// 克隆元素并添加新 props(如 `data-index`)和样式
return React.cloneElement(child, {
style: { border: '1px solid #ccc', padding: '8px', margin: '4px' },
'data-index': index,
});
}
return child; // 非 React 元素直接返回
})}
</div>
);
};
// 使用方式
const App = () => {
return (
<ListWithIndices>
<div>Item 1</div>
<div>Item 2</div>
<span>Item 3</span>
{"纯文本也会被渲染"}
</ListWithIndices>
);
};
关键点:
-
React.Children.map:安全遍历children(即使children是单个元素或数组)。 -
React.isValidElement:检查是否为合法的 React 元素(避免处理字符串、数字等原始类型)。 -
React.cloneElement:克隆元素并修改/添加 props。
1171

被折叠的 条评论
为什么被折叠?



