如何将className样式传递给react组件



每当我试图通过className道具将样式传递给我的Table组件时,它就会中断,不会呈现默认样式或传递的样式。如果我不通过className道具传递样式,Table的默认样式将显示良好。我尝试过用插值和串联来连接字符串,但没有成功。如果样式不是从另一个组件传下来的,则.join('')方法适用于多个样式。

我的表组件

import React from 'react';
import styles from './Table.module.scss';
const Table = ({ 
children,
className 
}: { 
children: React.ReactNode; 
className?: string 
}) => {
return <table className={[styles.table, className].join('')}>{children}</table>;
};

母组件

import React from 'react';
import styles from './PaymentTable.module.scss';
import Table '../Table';
interface Props {
children: React.ReactNode;
}
const PaymentTable: React.FC<Props> = ({ children }) => {
return (
<Table className={styles.paymentTable}>
{children}
</Table>
);
};
export default PaymentTable;

表Sass文件

@use 'shared/styles';
.table {
border-collapse: separate;
border-spacing: 0;
caption,
th,
td {
font-size: styles.em(14);
line-height: styles.em(17);
}
caption,
th {
font-weight: 600;
}
caption {
margin-bottom: 8px;
margin-top: 16px;
text-align: left;
}
th,
td {
text-align: center;
}
th {
background-color: styles.color(gray, 95);
padding: 8px 0px;
}
th:first-child {
border-top-left-radius: 8px;
}
th:last-child {
border-top-right-radius: 8px;
}
td {
border-bottom: 2px solid styles.color(gray, 95);
font-weight: 400;
padding: 18px 0px;
}
tr td:first-child {
border-left: 2px solid styles.color(gray, 95);
}
tr td:last-child {
border-right: 2px solid styles.color(gray, 95);
}
tr:last-child {
td:first-child {
border-bottom-left-radius: 8px;
}
td:last-child {
border-bottom-right-radius: 8px;
}
}
}

支付表Sass文件

.paymentTable {
tbody tr {
cursor: pointer;
}
}

您可以在一个字符串中将多个类名传递到className道具中。

父级:

const PaymentTable: React.FC<Props> = ({ children }) => {
return (
<Table className="paymentTable">
{children}
</Table>
);
};

儿童:

children,
className 
}: { 
children: React.ReactNode; 
className?: string 
}) => {
return <table className=`${styles.table} ${className}`>{children}</table>;
};

此外,您正在加入没有空格的classNames.join('')。如果你想坚持你的方法,你需要用.join(' ')来分割它们

最新更新