reactjs Ant Design表搜索定制

wpcxdonn  于 2023-01-02  发布在  React
关注(0)|答案(2)|浏览(144)

我正在使用Ant Design表,我使用getColumnSearchProps进行column-driven搜索。我希望在列的标题中有search input。但是我不知道如何处理对该列的搜索和输入?
数据:

const data = [
  {
    key: '1',
    name: 'John Brown',
    age: 32,
    address: 'New York No. 1 Lake Park',
  },
  {
    key: '2',
    name: 'Joe Black',
    age: 42,
    address: 'London No. 1 Lake Park',
  }]

这是我的专栏:

const columns = [
    {
        title: (
            <>
                <Search
                    placeholder="search"
                    prefix={<CPIcon type="search" />}
                    onChange={??????????????}
                />
                name
            </>
        ),
        dataIndex: 'name',
        key: '1',
        align: 'right',
        render: text => (<h1>{text}</h1>)
    },

    other columns ...
]

在渲染中:

<Table columns={columns} dataSource={data} />
zujrkrfu

zujrkrfu1#

Array.filter()String.includes()一起使用
另外,请注意Input.Search只添加了两个属性:onSearchenterButton,所以不使用任何附加 prop 渲染它是没有意义的。

export default function App() {
  const [dataSource, setDataSource] = useState(data);
  const [value, setValue] = useState('');

  const FilterByNameInput = (
    <Input
      placeholder="Search Name"
      value={value}
      onChange={e => {
        const currValue = e.target.value;
        setValue(currValue);
        const filteredData = data.filter(entry =>
          entry.name.includes(currValue)
        );
        setDataSource(filteredData);
      }}
    />
  );

  const columns = [
    {
      title: FilterByNameInput,
      dataIndex: 'name',
      key: '1'
    }
  ];

  return (
    <FlexBox>
      <Table columns={columns} dataSource={dataSource} />
    </FlexBox>
  );
}

mgdq6dx1

mgdq6dx12#

另一个答案真的有效吗?我实际上使用了一个额外的useCallback函数:

export default () => {
  const [data, setData] = useState(null)
  const [val, setVal] = useState('')

  const filterVals = useCallback((e) => {
    const currValue = e.target.value
    setVal(currValue)
    const filteredVals = data.filter(entry =>
      entry.val.includes(currValue)
    )
    setData(filteredVals)
  }, [loading])

  const columns = [
    {
      title:
        <Input
          placeholder="lalaland"
          value={val}
          onChange={filterVals}
        />,
      dataIndex: 'val',
    },
  ]

  return (
    <Table
      bordered
      dataSource={data}
      columns={columns}
    />
  )
}

相关问题