使用来自 React.Children 数组的包装器输出每个子项



我有这个可重用的组件。

export const ListItems = ({ controls, children }) => {
const content = controls ? <PrivateComponent>{ children }</PrivateComponent> : children;
return <ul>{ content }</ul>
}

看起来很漂亮直截了当。这个想法是,在 PrivateComponent 中,我想用一个额外的包装器包装每个子项,如下所示:

export const PrivateComponent = ({ children }) => {
const _children = React.Children.toArray(children);
return (
<div>{ _children.map(child => <SomeWrapper>{ child }</SomeWrapper> ) }</div>
);
}

我的问题是,以这种方式渲染孩子是正确的,还是应该使用 cloneElement?另外,我应该在map函数中使用什么来作为SomeWrapper的键?

这种方式渲染子级是否正确,还是应该使用 cloneElement?

您可以直接使用子实例,那里没有问题。只有当你想改变/添加任何道具或换掉它自己的子道具时,或者如果你需要重复的,因为你打算在DOM的两个不同位置插入"同一个子项",你需要一个副本。cloneElement

我应该在map函数中使用什么来表示SomeWrapper的键?

您可以使用React.Children.map(children, function[(thisArg)])(doc) 自动添加密钥。

最新更新