【问题标题】:React cloneElement on ReactElement's nested children在 ReactElement 的嵌套子元素上反应 cloneElement
【发布时间】:2023-01-28 03:23:31
【问题描述】:
我有这个嵌套有 TextInput 和 Box 的 react-admin 布局框
<Box>
<TextInput source="text1" />
<TextInput source="text2" />
<Box>
<TextInput source="text3" />
</Box>
</Box>
我如何基于以下嵌套框元素克隆元素:
Children.map(children, (child) => {
return cloneElement(child, {
className: 'my-class',
});
});
【问题讨论】:
标签:
reactjs
typescript
react-admin
【解决方案1】:
为了克隆嵌套的 Box 元素并使用 cloneElement 向其添加 className,您可以使用一个函数递归迭代 Box 元素的子元素并将 cloneElement 方法应用于每个子元素。
以下是如何执行此操作的示例:
function cloneWithClass(children) {
return Children.map(children, (child) => {
if (child.type === Box) {
return cloneElement(child, {
className: 'my-class',
children: cloneWithClass(child.props.children),
});
}
return cloneElement(child, { className: 'my-class' });
});
}
此函数将外部 Box 元素的子元素作为参数,并使用 Children.map 遍历它们。如果子元素的类型为 Box,它将对该子元素的子元素递归调用 cloneWithClass 函数,并将其作为克隆元素的新子元素传递。它将把 cloneElement 方法应用于 className: 'my-class' 的孩子。
然后你可以像这样在你的组件中使用这个函数:
<Box>
{cloneWithClass(children)}
</Box>
这将克隆所有嵌套的 Box 元素并向它们添加类“my-class”。