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

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

这是我当前的代码:

// 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;

两个组件数组作为输入传递到 Main 组件,我想为每个组件添加一个 class。该函数不知道这些组件是什么(即可能是按钮、链接、div 或其他组件),但可以断言它们都有一个 className 属性。我该如何实施?当我尝试上述操作时,出现了这个 linting 错误:

ESLint: Assignment to property of function parameter 'btn'.(no-param-reassign)

你应该使用 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}` })
  })
}