React中如何对比数组实现表格默认显示指定列?
React 表格默认显示指定列的实现方法
我需要在React中基于API返回的数据生成表格,默认只展示部分列。目前有两个数组:defaultColumns 存储默认要显示的列标识,headers 存储所有列的ID和标题信息。已经写了表格的基础代码,现在需要补充判断逻辑,确认当前列的ID是否在defaultColumns中,以此决定是否渲染该列。
原始定义代码
const defaultColumns = ["email", "rolename", "isActive"]; const headers = [ { id: "username", title: "User Name", }, { id: "name", title: "Name", }, { id: "email", title: "Email", applySort: true, }, { id: "siteName", title: "Site Name(s)", }, { id: "roleName", title: "Role(s)", }, ];
已完成的基础表格代码
<table className="table table-md table-striped table-bordered table-hover"> <thead> <tr> {headers.map((header, i) => { if (/* 需要补充判断header.id是否在defaultColumns中的条件 */) { return <th key={header.id}>{header.title}</th>; } })} </tr> </thead> <tbody> {props.data.map((row, index) => ( <tr key={index}> {headers.map((header, i) => { if (/* 需要补充判断header.id是否在defaultColumns中的条件 */) { return <td key={i}>{row[header.id]}</td>; } })} </tr> ))} </tbody> </table>
实现方案
1. 补充判断条件
使用数组的includes()方法检查列ID是否在默认列数组中。注意到defaultColumns里的rolename是全小写,而headers中对应列ID是roleName(驼峰),所以统一转小写避免大小写不匹配问题:
defaultColumns.includes(header.id.toLowerCase())
如果你的列ID大小写完全一致,也可以直接用defaultColumns.includes(header.id)。
2. 修改后的完整表格代码
<table className="table table-md table-striped table-bordered table-hover"> <thead> <tr> {headers.map((header, i) => { if (defaultColumns.includes(header.id.toLowerCase())) { return <th key={header.id}>{header.title}</th>; } })} </tr> </thead> <tbody> {props.data.map((row, index) => ( <tr key={index}> {headers.map((header, i) => { if (defaultColumns.includes(header.id.toLowerCase())) { return <td key={i}>{row[header.id] || '-'}</td>; } })} </tr> ))} </tbody> </table>
额外提示
- 若后续要支持用户自定义列显示,可把
defaultColumns改成useState状态变量,通过勾选组件修改数组,表格会自动更新列的显示。 - 给
row[header.id]加|| '-'兜底,避免API返回字段缺失时显示undefined。
内容的提问来源于stack exchange,提问作者Shashank gb
相关产品推荐
相关产品推荐

