自定义hooks拆分table内的columns

175 阅读1分钟

为达到优化代码,需要将table 组件内的columns拆分出去,达到减少一个js文件的代码量,方便维护

首先写一个column.js文件

    import { useMemo } from 'react'
    import { Button, Switch } from 'antd';
    const useColumns = (changeInfo, detailInfo) => {
      const content = useMemo(() => {
        return (
          [
            {
              title: '名称',
              dataIndex: 'name',
              key: 'name',
              ellipsis: true,
            },
            {
              title: '排序',
              dataIndex: 'age',
              key: 'age',
              ellipsis: true,
            },
            {
              title: '备注',
              dataIndex: 'address',
              key: 'address',
              ellipsis: true,
            },
            {
              title: '启用',
              dataIndex: 'classify',
              key: 'classify',
              render: (text, record) => {
                return <Switch checked={record.classify ? true : false} />;
              },
            },
            {
              title: '操作',
              dataIndex: 'address',
              key: 'address',
              render: (text, record) => {
                return (
                  <span>
                    <Button type='primary' onClick={() => changeInfo(record)} style={{ marginRight: '10px' }}>
                      编辑
                    </Button>
                    <Button type='primary' onClick={() => detailInfo(record)}>
                      详情
                    </Button>
                  </span>
                );
              },
            },
          ]
        )
      }, [changeInfo, detailInfo]);
      return content;
    }

    export default useColumns;

将column.js文件引入

      import useColumns from './column';
    
      const NewsCategory = () => {
          
           const changeInfo = (record) => {
            setNewsVisible(true);
            setModalTitle('change');
            setActiveData(record);
          };

          const detailInfo = (record) => {
            history.push({
              pathname: '/detail',
              query: { record, type: 'newsCategory' },
            });
          };

        const newcolumns = useColumns(changeInfo,detailInfo)
        
        return (
             <Table
              rowKey={(record) => record.key}
              columns={newcolumns}
              dataSource={data}
              rowSelection={{ ...rowSelection }}
              pagination={officeTotal > 10 ? pagination : false}
            />
        )
      }
     
    export default NewsCategory;
    

遇到的问题:

因为column文件中有编辑按钮之类的函数,需要将这些函数当做参数带入。不能直接将引入的方法直接放在table 的column属性上,因为这类函数有设置的状态之类的,需要重新声明newColumn。