在我的 React Ag 网格中,我有一列包含文本部分,后跟可选的徽章/图像。 使用这篇文章中的提示,我们可以向列添加省略号,如果该列只有文本数据,这可以正常工作。
对于我的场景,所需的行为如下,当用户调整列或窗口大小时,文本部分中的省略号应动态移动而不隐藏徽章。
|小文字(徽章)|
|一些 lo...(徽章)|
|这里也有长文本|
当用户展开列时,它应该看起来像
|这里有小文字! (徽章)|
|一些更长的...(徽章)|
|长文本这里没有徽章 |
为此,我正在考虑为 columnDefs 中的列添加自定义 cellRenderer,然后将其定义为两个跨度的 div(一个用于省略号/nowrap 文本,另一个用于可选徽章/图像)。
但是,为了控制文本范围的宽度,我可能必须在 column?.getActualWidth() 上使用 UseEffect,然后维护状态“columnWidth”,使用它我可以指定文本范围的宽度。
const NoWrapText = styled('span', (props: { width: number }) => ({
overflow: 'hidden',
textOverflow: 'ellipsis',
display: 'inline-block',
whiteSpace: 'nowrap',
maxWidth: props.width,
}));
export const CellRenderer = (props: ICellRendererParams) => {
const [columnWidth, setColumnWidth] = useState(props.column?.getActualWidth());
const isBadgeNeeded = checkIfBadgeIsNeededFunc(prop);
const widthToSet = !isBadgeNeeded ? columnWidth - 40 : columnWidth - 100;
useEffect(() => {
const actualColumnWidth = props.column?.getActualWidth();
if (actualColumnWidth) {
setColumnWidth(actualColumnWidth);
}
}, [props.column?.getActualWidth()]);
return (
<div>
<NoWrapText width={widthToSet}>props.value</NoWrapText>
<span><Badge></Badge></span>
</div>
);
};
export const colDef = [
{
headerName: 'header name',
enableRowGroup: true,
field: 'name',
rowGroupIndex: 2,
hide: true,
cellRenderer: 'cellRenderer',
},
{
headerName: 'header id',
enableRowGroup: true,
field: 'id',
rowGroupIndex: 1,
hide: true,
cellRenderer: 'cellRenderer',
},
];
const onGridSizeChanged = (params: any): void => {
if (gridParams.api) {
params.api.redrawRows();
params.api.sizeColumnsToFit();
}
};
我必须对所有列执行此操作,因此必须为每列存储不同的状态变量。
还有更好的方法来实现这一切吗?
使用 Flexbox 将单元格拉伸到列的宽度
.badge-icon {
width: 16px;
height: 16px;
border-radius: 50%;
background-color: #ccc;
}
table {
width: 50%;
table-layout: fixed;
}
.cell {
display: flex;
align-items: center;
justify-content: stretch;
}
.nowrap {
flex: auto;
width: 0;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
.badge {
flex: none;
margin-left: 4px;
}
<table>
<tbody>
<tr>
<td>1</td>
<td class="cell">
<span class="nowrap">Short text</span>
<span class="badge"><div class="badge-icon"></div></span>
</td>
</tr>
<tr>
<td>2</td>
<td class="cell">
<span class="nowrap">Somewhat longer text without a badge</span>
</td>
</tr>
<tr>
<td>3</td>
<td class="cell">
<span class="nowrap">Longer text with a badge</span>
<span class="badge"><div class="badge-icon"></div></span>
</td>
</tr>
</tbody>
</table>