【问题标题】:Looping through custom react components and adding className's to them循环通过自定义反应组件并向它们添加类名
【发布时间】:2020-09-05 06:46:23
【问题描述】:

我想使用.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】:

    children 属性是一个ReactElement(一个对象不是一个数组)。

    您需要使用React.Children API 才能映射children

    然后使用React.cloneElement 传递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>
      );
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-20
      • 1970-01-01
      • 1970-01-01
      • 2015-05-23
      • 1970-01-01
      相关资源
      最近更新 更多