简体   繁体   English

如何将 class 添加到 React 组件数组中的每个元素?

[英]How do I add a class to each element in an array of React Components?

This is my current code:这是我当前的代码:

// src/components/Main.tsx
import * as React from 'react';
import { ReactElement } from 'react';

import * as styles from '../styles/Main.module.scss';

type MainProps = {
  leftBtnGroup: ReactElement[],
  rightBtnGroup: ReactElement[],
  children: string,
};

const Main = ({ leftBtnGroup, rightBtnGroup, children }: MainProps) => (
  <>
    <div className={styles.main__btnBar}>
      <div className={styles.main__btnBar__leftBtnGrp}>
        {
          leftBtnGroup.map((btn) => {
            btn.props.className += ` ${styles.main__btnBar__btn}`;

            return btn;
          })
        }
      </div>
      <div className={styles.main__btnBar__rightBtnGrp}>
        {
          rightBtnGroup.map((btn) => {
            btn.props.className += ` ${styles.main__btnBar__btn}`;

            return btn;
          })
        }
      </div>
    </div>
    {children}
  </>
);

export default Main;

Two arrays of components are passed into the Main component as input and I want to add a class to each of these components.两个 arrays 组件作为输入传递到Main组件中,我想为每个组件添加一个 class。 The function does not know what these components are (ie could be buttons, links, divs, or other components) but it can be asserted that they all have a className prop. function 不知道这些组件是什么(即可能是按钮、链接、div 或其他组件),但可以断言它们都有一个className属性。 How can I implement this?我该如何实施? When I tried the above, I got this linting error:当我尝试上述方法时,我得到了这个 linting 错误:

ESLint: Assignment to property of function parameter 'btn'.(no-param-reassign) ESLint:分配给 function 参数“btn”的属性。(无参数重新分配)

You should probably use React.cloneElement ( https://reactjs.org/docs/react-api.html#cloneelement )您可能应该使用React.cloneElement ( https://reactjs.org/docs/react-api.html#cloneelement )

{
  leftBtnGroup.map(btn => {
    // I used ?? but you can use your choice of checking for existing
    // classes. Without checking, if they have no existing class this
    // would add an 'undefined' class where the existing classes go.
    return React.cloneElement(btn, { className: `${btn.props.className ?? ''} ${styles.main__btnBar__btn}` })
  })
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM