И пример создания таблицы TypeScript getColumnSearchProps - PullRequest
0 голосов
/ 27 мая 2020

Я использую следующий компонент муравья: https://ant.design/components/table/, и мне очень трудно добавить следующую опцию поиска в мою таблицу: enter image description here вот таблица i на данный момент создано: enter image description here

Я новичок как в React, так и в Typescript, так как проекта нет в js, но в машинописном тексте я не могу получить свой код работать правильно, просматривая документацию по муравью; Я превратил свой компонент в функциональный, так как я собираюсь использовать хуки, и добавил код, чтобы избавиться от большинства ошибок компилятора (объявление типа для ts), все еще есть некоторые синтаксические ошибки:

heres мой код:

import React,  { Component, useState } from 'react';
import {connect} from "react-redux";

// @ts-ignore
import Highlighter from 'react-highlight-words';

//**External Libraries */
//REACT MOSAIC
import {ExpandButton, MosaicWindow, RemoveButton} from "react-mosaic-component";
import {MosaicBranch} from "react-mosaic-component/src/types";

//BLUEPRINTJS
import {InputGroup} from "@blueprintjs/core";

//ANTDESIGN
import { Table , Button  ,Tag , Input , Space} from "antd";
import 'antd/dist/antd.css'; // or 'antd/dist/antd.less'
import {CaretRightOutlined , SearchOutlined} from '@ant-design/icons';

//STYLES
import './styles.css'

//API
import {useGetAllUtenti} from '../../../api/index';
import { Utente } from '../../../api/types';

const  UserSummaryWindow: React.FC<any> = (props) => {

  //HOOKS STATE FOR TABLE SEARCH
  const [searchText , setSearchText] = useState('');
  const [searchedColumn , setSearchedColumn] = useState('');

  const {path} = props;

  const dataSource: Object | any = useGetAllUtenti().data;

  const ruoli: any = [
    {
      text: 'User',
      value: 'user',
    },
    {
      text: 'Administrator',
      value: 'administrator',
    },
    {
      text: 'NumeroVerde',
      value: 'numeroVerde',
    },
  ]

  const stati: any = [
    {
      text: 'Attivo',
      value: 1,
    },
    {
      text: 'Non Attivo',
      value: 0,
    }
  ]

  const columns: any = [

    {
      title: 'Nome',
      dataIndex: 'nome',
      key: 'nome',
      defaultSortOrder: 'descend',
      sorter: (a:any, b:any) => { return a.nome.localeCompare(b.nome)},
    },
    {
      title: 'Cognome',
      dataIndex: 'cognome',
      key: 'cognome',
      sorter: (a:any, b:any) => { return a.cognome.localeCompare(b.cognome)},
    },
    {
      title: 'Ruolo',
      dataIndex: 'ruolo',
      key: 'ruolo',
      filters: ruoli,
      onFilter: (value:any, record:any) => record.ruolo.indexOf(value) === 0,
      sorter: (a:any, b:any) => { return a.ruolo.localeCompare(b.ruolo)},
      render: (text: string) => (
        <>        
          {
                <Tag color={renderTagColor(text)}>
                  {text.toUpperCase()}
                </Tag>
          }
        </>)
    },
    {
      title: 'Gestore',
      dataIndex: 'gestore',
      key: 'gestore',
      sorter: (a:any, b:any) => { return a.gestore.localeCompare(b.gestore)},
    },
    {
      title: 'Username',
      dataIndex: 'username',
      key: 'username',
      sorter: (a:any, b:any) => { return a.username.localeCompare(b.username)},
    },
    // {
    //   title: 'Password',
    //   dataIndex: 'password',
    //   key: 'password',
    // },
    // {
    //   title: 'IDEnte',
    //   dataIndex: 'idEnte',
    //   key: 'idEnte',
    // },
    {
      title: 'Tipo',
      dataIndex: 'tipo',
      key: 'tipo',
      sorter: (a:any, b:any) => a.tipo - b.tipo,
    },
    {
      title: 'Stato',
      dataIndex: 'stato',
      key: 'stato',
      filters: stati,
      onFilter: (value:any, record:any) => record.stato.indexOf(value) === 0,
      sorter: (a:any, b:any) => a.stato - b.stato,
      render :(stato: number) => (
        <>
          {
            (stato == 1) ? 
              (
                <Tag color="#00cc00">
                  Attivo
                </Tag>
              ) :
              (
                <Tag color="#ff0000">
                  Non Attivo
                </Tag>
              ) 
          }
        </>)
    },
    {
      title: 'Ultimo aggiornamento password',
      dataIndex: 'ultimoAggiornamentoPassword',
      key: 'ultimoAggiornamentoPassword',
      sorter: (a:any, b:any) => a.ultimoAggiornamentoPassword.localeCompare(b.ultimoAggiornamentoPassword)
    },
    {
      title: '',
      dataIndex: 'idUtente',
      key: 'idUtente',
      render: () => (
        //da inserire link per andare al dettaglio / modifica utente
        <Button type="primary"><CaretRightOutlined /></Button>  
      ),
    },
  ]

  const toolbarControls = React.Children.toArray([
    <ExpandButton/>,
    <RemoveButton/>
  ]);

  function renderTagColor(text:string): string {
    switch(text) {
      case 'user':
        return 'gold';
      case 'administrator':
        return 'red';
      case 'numeroVerde':
        return 'green';
      default:
        return '';
    }
  }

  getColumnSearchProps = dataIndex => ({
    filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
      <div style={{ padding: 8 }}>
        <Input
          ref={node => {
            this.searchInput = node;
          }}
          placeholder={`Search ${dataIndex}`}
          value={selectedKeys[0]}
          onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
          onPressEnter={() => this.handleSearch(selectedKeys, confirm, dataIndex)}
          style={{ width: 188, marginBottom: 8, display: 'block' }}
        />
        <Space>
          <Button
            type="primary"
            onClick={() => handleSearch(selectedKeys, confirm, dataIndex)}
            icon={<SearchOutlined />}
            size="small"
            style={{ width: 90 }}
          >
            Search
          </Button>
          <Button onClick={() => handleReset(clearFilters)} size="small" style={{ width: 90 }}>
            Reset
          </Button>
        </Space>
      </div>
    ),
    filterIcon: filtered => <SearchOutlined style={{ color: filtered ? '#1890ff' : undefined }} />,
    onFilter: (value, record) =>
      record[dataIndex].toString().toLowerCase().includes(value.toLowerCase()),
    onFilterDropdownVisibleChange: visible => {
      if (visible) {
        setTimeout(() => this.searchInput.select());
      }
    },
    render: (text:string) =>
      searchText === dataIndex ? (
        <Highlighter
          highlightStyle={{ backgroundColor: '#ffc069', padding: 0 }}
          searchWords={[searchText]}
          autoEscape
          textToHighlight={text.toString()}
        />
      ) : (
        text
      ),
  });

  function handleSearch (selectedKeys:any, confirm:any, dataIndex:any) {
    confirm();
    setSearchText(selectedKeys[0]);
    setSearchedColumn(dataIndex);
  };

  function handleReset (clearFilters:any) {
    clearFilters();
    setSearchText('');
  };

  return (
    <MosaicWindow<string>
      title="Riepilogo Utenti"
      path={path}
      toolbarControls={toolbarControls}
    >
      <Table 
      dataSource={dataSource} 
      columns={columns} 
      bordered={true}
      //pagination={{ pageSize:3,position: ['bottomCenter'] }}
      pagination={{position: ['bottomCenter'] }}
      rowKey={'idUtente'}
      //stile per righe striped
      rowClassName={(record, index) => index % 2 === 0 ? 'table-row-light' :  'table-row-dark'}
      />
    </MosaicWindow>
  );
};


export default UserSummaryWindow;

Часть, которая вызывает у меня головную боль (необходимо преобразовать ее в машинописный текст [строгий параметр в файле конфигурации включен]):

getColumnSearchProps = dataIndex => ({
    filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
      <div style={{ padding: 8 }}>
        <Input
          ref={node => {
            this.searchInput = node;
          }}
          placeholder={`Search ${dataIndex}`}
          value={selectedKeys[0]}
          onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
          onPressEnter={() => this.handleSearch(selectedKeys, confirm, dataIndex)}
          style={{ width: 188, marginBottom: 8, display: 'block' }}
        />
        <Space>
          <Button
            type="primary"
            onClick={() => handleSearch(selectedKeys, confirm, dataIndex)}
            icon={<SearchOutlined />}
            size="small"
            style={{ width: 90 }}
          >
            Search
          </Button>
          <Button onClick={() => handleReset(clearFilters)} size="small" style={{ width: 90 }}>
            Reset
          </Button>
        </Space>
      </div>
    ),
    filterIcon: filtered => <SearchOutlined style={{ color: filtered ? '#1890ff' : undefined }} />,
    onFilter: (value, record) =>
      record[dataIndex].toString().toLowerCase().includes(value.toLowerCase()),
    onFilterDropdownVisibleChange: visible => {
      if (visible) {
        setTimeout(() => this.searchInput.select());
      }
    },
    render: (text:string) =>
      searchText === dataIndex ? (
        <Highlighter
          highlightStyle={{ backgroundColor: '#ffc069', padding: 0 }}
          searchWords={[searchText]}
          autoEscape
          textToHighlight={text.toString()}
        />
      ) : (
        text
      ),
  });

Я здесь я не прошу вас исправить мой код, просто хотел узнать, может ли кто-нибудь поделиться машинописной реализацией этой функции getColumnSearchProps или примером компонента таблицы из проекта ant с машинописным кодом ..

...