[英]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;
兩個 arrays 組件作為輸入傳遞到Main
組件中,我想為每個組件添加一個 class。 function 不知道這些組件是什么(即可能是按鈕、鏈接、div 或其他組件),但可以斷言它們都有一個className
屬性。 我該如何實施? 當我嘗試上述方法時,我得到了這個 linting 錯誤:
ESLint:分配給 function 參數“btn”的屬性。(無參數重新分配)
您可能應該使用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.