Javascript 通过自定义react组件循环并添加className';向他们致敬

Javascript 通过自定义react组件循环并添加className';向他们致敬,javascript,reactjs,array.prototype.map,Javascript,Reactjs,Array.prototype.map,我想使用.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="Cli

我想使用
.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)"/>
我尝试实现循环,如下所示:

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

//

<div>{newChildren}</div>
const newChildren=children.map((项)=>{
//将类名添加到每个项
})
//
{newChildren}

然而,我被困在这一点上。如何将
className
attr添加到所有项目中?

children
prop是一个
ReactElement
(一个对象,而不是数组)

您需要使用才能映射
子对象

然后用于传递
className
属性

工作示例:

// styles.js
.button {
  background: red;
}

// App.js
import "./style.css";

const Container = ({ children }) => {
  return (
    <div>
      {React.Children.map(children, (child, key) =>
        React.cloneElement(child, { className: "button", key })
      )}
    </div>
  );
};

const App = () => {
  return (
    <Container>
      <button>Give me some color!</button>
    </Container>
  );
};
//styles.js
.按钮{
背景:红色;
}
//App.js
导入“/style.css”;
常量容器=({children})=>{
返回(
{React.Children.map(Children,(child,key)=>
cloneElement(子级,{className:“button”,key})
)}
);
};
常量应用=()=>{
返回(
给我点颜色!
);
};

儿童
道具是一个
元素
(一个对象,而不是一个数组)

您需要使用才能映射
子对象

然后用于传递
className
属性

工作示例:

// styles.js
.button {
  background: red;
}

// App.js
import "./style.css";

const Container = ({ children }) => {
  return (
    <div>
      {React.Children.map(children, (child, key) =>
        React.cloneElement(child, { className: "button", key })
      )}
    </div>
  );
};

const App = () => {
  return (
    <Container>
      <button>Give me some color!</button>
    </Container>
  );
};
//styles.js
.按钮{
背景:红色;
}
//App.js
导入“/style.css”;
常量容器=({children})=>{
返回(
{React.Children.map(Children,(child,key)=>
cloneElement(子级,{className:“button”,key})
)}
);
};
常量应用=()=>{
返回(
给我点颜色!
);
};