如何在react-table中根据数据值为单个单元格设置自定义样式
react-table 根据字段值设置单元格样式实现方案
方案1:修改Status列配置(更推荐)
该方案仅针对Status列生效,逻辑与列绑定,后续维护成本更低。你可以选择自定义内部元素样式,也可以直接给td加样式:
自定义Cell内容样式
export const COLUMNS = [ { Header: 'Date', accessor: 'transactionDate', }, { Header: 'Amount', accessor: 'amount', }, { Header: 'Status', accessor: 'status', // 新增自定义Cell渲染逻辑 Cell: ({ value }) => { const textColor = value === 'SUCCESS' ? 'green' : 'red'; return <span style={{ color: textColor }}>{value}</span>; } }, ];
直接给td设置样式
export const COLUMNS = [ { Header: 'Date', accessor: 'transactionDate', }, { Header: 'Amount', accessor: 'amount', }, { Header: 'Status', accessor: 'status', // 给当前列的td元素绑定样式 getCellProps: ({ cell: { value } }) => ({ style: { color: value === 'SUCCESS' ? 'green' : 'red' } }) }, ];
方案2:修改td渲染逻辑
如果不想改动列配置,可以直接在表格渲染处统一处理:
<tbody {...getTableBodyProps()}> {rows.map(row => { prepareRow(row); return ( <tr {...row.getRowProps()}> {row.cells.map(cell => { const cellProps = cell.getCellProps(); // 仅处理Status列 if (cell.column.id === 'status') { const textColor = cell.value === 'SUCCESS' ? 'green' : 'red'; cellProps.style = { ...cellProps.style, color: textColor }; } return <td {...cellProps}>{cell.render('Cell')}</td>; })} </tr> ); })} </tbody>
内容的提问来源于stack exchange,提问作者Vish
相关产品推荐
相关产品推荐

