react-table中如何根据数值渲染不同颜色的圆形标识
react-table 实现评论等级彩色圆形标识方案
react-table 支持通过列配置的Cell属性完全自定义单元格渲染内容,完全可以实现你要的效果,实现逻辑和你现有代码中为Dishes列自定义渲染菜品文本的方式一致,具体操作如下:
- 首先定义评论等级和对应展示颜色的映射表,色值可以根据你的设计需求自行修改:
const levelColor = { 1: '#ef4444', // 1级对应红色 2: '#f97316', // 2级对应橙色 3: '#eab308', // 3级对应黄色 4: '#22c55e' // 4级对应绿色 }
- 根据你的展示需求选择对应渲染方式:
- 方案1:单独新增一列展示等级标识
在你现有的columns(也就是代码里命名为data的列配置数组)中,插入如下列配置即可,注意把commentLevel替换成你实际数据中存储评论等级的字段名:
{ Header: "评论等级", accessor: row => row.commentLevel, id: "commentLevel", Cell: ({ value }) => { // 无效值兜底 if (!levelColor[value]) return null return ( <div style={{ width: 16, height: 16, borderRadius: '50%', backgroundColor: levelColor[value] }} /> ) } }- 方案2:把等级标识和评论内容放在同一列展示
直接修改原有Comments列的配置,增加自定义Cell渲染逻辑:
{ Header: "Comments", accessor: row => row.comments, Cell: ({ row }) => { const level = row.original.commentLevel // 替换为实际的等级字段名 return ( <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}> <div style={{ width: 16, height: 16, borderRadius: '50%', backgroundColor: levelColor[level] || '#ccc' }} /> <span>{row.original.comments}</span> </div> ) } }, - 方案1:单独新增一列展示等级标识
- 补充:你代码中定义的
getRowProps行样式方法目前没有传入Table组件,如果需要选中行高亮的效果,记得给Table组件加上该属性:
<Table data={matchData} columns={data} getRowProps={getRowProps} />
内容的提问来源于stack exchange,提问作者Zokulko
相关产品推荐
相关产品推荐

