react、antd制作查询表格,没有端口,直接给的数据
时间: 2024-03-25 14:35:59 浏览: 112
antd table按表格里的日期去排序操作
如果没有后端接口,而是直接给了数据,那么可以在前端使用 mock 数据来模拟接口请求,然后将数据渲染到表格中。下面是一个使用 React 和 Ant Design 制作查询表格的示例代码:
```jsx
import React, { useState } from 'react';
import { Table, Input, Button } from 'antd';
const data = [
{ id: 1, name: '张三', age: 18, gender: '男' },
{ id: 2, name: '李四', age: 20, gender: '女' },
{ id: 3, name: '王五', age: 22, gender: '男' },
{ id: 4, name: '赵六', age: 24, gender: '女' },
];
function SearchTable() {
const [searchText, setSearchText] = useState('');
const [searchedColumn, setSearchedColumn] = useState('');
const [dataSource, setDataSource] = useState(data);
const handleSearch = (selectedKeys, confirm, dataIndex) => {
confirm();
setSearchText(selectedKeys[0]);
setSearchedColumn(dataIndex);
};
const handleReset = clearFilters => {
clearFilters();
setSearchText('');
};
const getColumnSearchProps = dataIndex => ({
filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
<div style={{ padding: 8 }}>
<Input
placeholder={`Search ${dataIndex}`}
value={selectedKeys[0]}
onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
onPressEnter={() => handleSearch(selectedKeys, confirm, dataIndex)}
style={{ width: 188, marginBottom: 8, display: 'block' }}
/>
<Button
type="primary"
onClick={() => handleSearch(selectedKeys, confirm, dataIndex)}
icon="search"
size="small"
style={{ width: 90, marginRight: 8 }}
>
Search
</Button>
<Button onClick={() => handleReset(clearFilters)} size="small" style={{ width: 90 }}>
Reset
</Button>
</div>
),
filterIcon: filtered => (
<Icon type="search" 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 =>
searchedColumn === dataIndex ? (
<Highlighter
highlightStyle={{ backgroundColor: '#ffc069', padding: 0 }}
searchWords={[searchText]}
autoEscape
textToHighlight={text.toString()}
/>
) : (
text
),
});
const columns = [
{
title: 'ID',
dataIndex: 'id',
sorter: (a, b) => a.id - b.id,
...getColumnSearchProps('id'),
},
{
title: '姓名',
dataIndex: 'name',
sorter: (a, b) => a.name.localeCompare(b.name),
...getColumnSearchProps('name'),
},
{
title: '年龄',
dataIndex: 'age',
sorter: (a, b) => a.age - b.age,
...getColumnSearchProps('age'),
},
{
title: '性别',
dataIndex: 'gender',
sorter: (a, b) => a.gender.localeCompare(b.gender),
...getColumnSearchProps('gender'),
},
];
return <Table dataSource={dataSource} columns={columns} />;
}
export default SearchTable;
```
这里的 `data` 变量存储了我们需要展示的数据,可以根据实际情况进行修改。在 `SearchTable` 组件中,我们使用了 `useState` hook 来管理搜索框的状态和数据源,`getColumnSearchProps` 函数用于生成带搜索功能的列配置。最后,我们将数据源和列配置传递给 `Table` 组件即可。
阅读全文