React中动态控制Ant Design Table列的显示与隐藏

需求:动态控制Table列的显示与隐藏,当isAge为true时,显示年龄列

在这里插入图片描述

方法一:

  import { useMemo } from 'react'
  let isAge = false
  
  const data = [
    {
      name: '小明',
      sex: '男',
      age: '12',
      class: '4年级1班'
    }
  ]

  const columns = useMemo(() => {
    const baseColumns = [
      {
        title: '姓名',
        dataIndex: 'name'
      },
      {
        title: '性别',
        dataIndex: 'sex'
      },
      {
        title: '班级',
        dataIndex: 'class'
      }
    ]
    if (isAge) {
      // 在性别列后添加年龄列
      baseColumns.splice(2, 0, {
        title: '年龄',
        dataIndex: 'age'
      })
    }
    return baseColumns
  })
  
  <Table columns={columns} size="small" dataSource={data} />

方法二:(推荐)

  let isAge = false
  
  const data = [
    {
      name: '小明',
      sex: '男',
      age: '12',
      class: '4年级1班'
    }
  ]

 // 当isAge为false时,columns隐藏年龄列
  const columns = [
    {
      title: '姓名',
      dataIndex: 'name'
    },
    {
      title: '性别',
      dataIndex: 'sex'
    },
    isAge && {
      title: '年龄',
      dataIndex: 'age'
    },
    {
      title: '班级',
      dataIndex: 'class'
    }
  ].filter(Boolean)// 当isAge为false时,columns需要去掉false项
  
  <Table columns={columns} size="small" dataSource={data} />

方法三:

  let isAge = false
  
  const data = [
    {
      name: '小明',
      sex: '男',
      age: '12',
      class: '4年级1班'
    }
  ]

  const columns = [
    {
      title: '姓名',
      dataIndex: 'name'
    },
    {
      title: '性别',
      dataIndex: 'sex'
    },
    {
      title: '年龄',
      dataIndex: 'age'
    },
    {
      title: '班级',
      dataIndex: 'class'
    }
  ]
  
  <Table 
    columns={
      //在这里做判断
      !isAge ? columns.filter((item) => item.dataIndex !== 'age') : columns
    } 
    size="small"
    dataSource={data} 
  />

效果图

在这里插入图片描述

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐