我建议使用“classnames”包在 React 中应用 BEM,因为向组件添加条件类/修饰符要容易得多。但要回答你的问题,我可能会这样做:
import React from 'react';
import classnames from 'classnames';
const TableHead = ({ title, center = false }) => {
const styling = classnames({
'cp-table-head': !center,
'cp-table-head--center': center,
});
return <th className={styling}>{title}</th>
}
const Table = () => {
const columns = ['Name', 'Title', 'Position', 'Company'];
const headers = columns.map((title) => (
<TableHead key={title} title={title} center />
));
return (
<table>
<thead>
<tr>
{headers}
</tr>
</thead>
<tbody>
<tr>
<td>body..</td>
</tr>
</tbody>
</table>
)
}
这个例子比较简单,所以你可以选择只使用三元运算符:
className={`cp-table-head${center ? '--center' : ''}`}
要回答有关将特定标题项居中的问题。您可以将上述TableHead 组件与...一起使用:
...
const Table = () => {
const columns = [
{
title: 'Name',
center: true,
},
{
title: 'Title',
center: false,
},
{
title: 'Position',
center: true,
},
{
title: 'Company',
center: false,
}
];
const headers = columns.map((header, index) => (
<TableHead key={index} title={header.title} center={header.center} />
));
...