Antd相关 Table表格自定义点击单元格(列)展开功能

起初参考网上其它写法,符号+失效需要隐藏,点击事件需要render实现,的是代码运行结果失败,点击没效果,研究API进行了改良……
改由单元格点击触发事件(不受render内容限制),且+号功能可同步使用(不用隐藏)

import React from "react";
import {
      Table } from "antd";

class TableEx extends React.Component {
     
  constructor(props) {
     
    super(props);
    this.state = {
      expandedRowKeys: [] };
  }

  expandRowByKey = (key) => {
     
    const {
      expandedRowKeys } = this.state;
    // const index = expandedRowKeys.findIndex((item) => key === item);
    // if (index > -1) expandedRowKeys.splice(index, 1);
    // else expandedRowKeys.push(key);
    // this.setState({ expandedRowKeys }); //注释部分是网上写法,运行并没有效果
    let keys = [...expandedRowKeys]; // 最后发现这的问题,坑了我半天时间
    if (index > -1) keys = keys.filter((item) => key !== item);
    else keys.push(key);
    this.setState({
      expandedRowKeys: keys });
  };
  onExpand = (expanded, record) => {
     
    this.expandRowByKey(record.key);
  };

  render() {
     
    const {
      expandedRowKeys } = this.state;
    const columns = [
      {
      title: "Name", dataIndex: "name", key: "name" },
      {
      title: "Age", dataIndex: "age", key: "age" },
      {
      title: "Address", dataIndex: "address", key: "address" },
      {
     
        title: "Action",
        dataIndex: "",
        key: "x",
        render: () => <a>Delete</a>,
        onCell: (record) => {
     
          return {
     
            onClick: () => this.expandRowByKey(record.key),
          };
        },
      },
    ];
    const data = [
      {
     
        key: 1,
        name: "John Brown",
        age: 32,
        address: "New York No. 1 Lake Park",
        description:
          "My name is John Brown, I am 32 years old, living in New York No. 1 Lake Park.",
      },
      {
     
        key: 2,
        name: "Jim Green",
        age: 42,
        address: "London No. 1 Lake Park",
        description:
          "My name is Jim Green, I am 42 years old, living in London No. 1 Lake Park.",
      },
      {
     
        key: 3,
        name: "Not Expandable",
        age: 29,
        address: "Jiangsu No. 1 Lake Park",
        description: "This not expandable",
      },
      {
     
        key: 4,
        name: "Joe Black",
        age: 32,
        address: "Sidney No. 1 Lake Park",
        description:
          "My name is Joe Black, I am 32 years old, living in Sidney No. 1 Lake Park.",
      },
    ];
    console.log(expandedRowKeys);
    return (
      <Table
        columns={
     columns}
        expandable={
     {
     
          expandedRowKeys: expandedRowKeys,
          onExpand: this.onExpand,
          expandedRowRender: (record) => (
            <p style={
     {
      margin: 0 }}>{
     record.description}</p>
          ),
        }}
        dataSource={
     data}
      />
    );
  }
}

你可能感兴趣的:(Antd相关,react,javascript)