React中的antd的表格使用方法

发布于:2025-07-24 ⋅ 阅读:(14) ⋅ 点赞:(0)
import React from "react";
import { Space, Table, Tag } from "antd";

// 定义表格列配置
const columns = [
  {
    title: 'Name',
    dataIndex: 'name',
    key: 'name',
    // 渲染姓名列为可点击链接样式
    render: text => <a>{text}</a>,
  },
  {
    title: 'Age',
    dataIndex: 'age',
    key: 'age',
  },
  {
    title: 'Address',
    dataIndex: 'address',
    key: 'address',
  },
  {
    title: 'Tags',
    key: 'tags',
    dataIndex: 'tags',
    // 渲染标签列表,根据标签长度和内容设置不同颜色
    render: (_, { tags }) => (
      <>
        {tags.map(tag => {
          // 根据标签长度动态设置颜色,长度大于5为蓝色,默认绿色
          let color = tag.length > 5 ? 'geekblue' : 'green';
          // 特殊标签"loser"设置为红色
          if (tag === 'loser') {
            color = 'volcano';
          }
          return (
            <Tag color={color} key={tag}>
              {tag.toUpperCase()}
            </Tag>
          );
        })}
      </>
    ),
  },
  {
    title: 'Action',
    key: 'action',
    // 渲染操作列,包含邀请和删除按钮
    render: (_, record) => (
      <Space size="middle">
        <a>Invite {record.name}</a>
        <a>Delete</a>
      </Space>
    ),
  },
];

// 定义表格数据源
const data = [
  {
    key: '1',
    name: 'John Brown',
    age: 32,
    address: 'New York No. 1 Lake Park',
    tags: ['nice', 'developer'],
  },
  {
    key: '2',
    name: 'Jim Green',
    age: 42,
    address: 'London No. 1 Lake Park',
    tags: ['loser'],
  },
  {
    key: '3',
    name: 'Joe Black',
    age: 32,
    address: 'Sydney No. 1 Lake Park',
    tags: ['cool', 'teacher'],
  },
];

// 主应用组件,渲染带配置的表格
const App = () => <Table columns={columns} dataSource={data} />;

export default App;

展示

 


网站公告

今日签到

点亮在社区的每一天
去签到