遍历自定义的react组件并向其添加className的组件

问题描述 投票:0回答:1

我想使用.map()遍历自定义的React元素。我正在遍历的一个示例是:

<Button text="Click me" />
<Button text="Click me" bgColor="yellow" textColor="black"/>
<Button text="Click me" bgColor="limeGreen" onClick={() => console.log('clicked')}/>
<Button text="Click me" bgColor="orchid"/>
<Button text="Click me" bgColor="rgb(150, 20,0)"/>

我有一个名为Container的组件,它将这些子代作为属性:

export const Container = ({children}) => {

    return (
        <div>{children}</div>
    )
}

我试图实现像这样的循环:

const newChildren = children.map((item) => {
    //add class name to every item
})

//

<div>{newChildren}</div>

但是我在这一点上仍然停留。如何为所有项目添加className attr?

javascript reactjs array.prototype.map
1个回答
1
投票

children prop是一个ReactElementobjectnot一个数组)。

您需要使用React.Children API映射React.Children并使用children传递React.cloneElement属性。

工作示例:

React.cloneElement

className

© www.soinside.com 2019 - 2024. All rights reserved.