一、可选择和操作表格
类式 -> 函数式组件
import {Component, useState} from "react";
import {Table, Button} from 'antd';
const columns = [
{
title: 'Name',
dataIndex: 'name',
},
{
title: 'Age',
dataIndex: 'age',
},
{
title: 'Address',
dataIndex: 'address',
},
];
const data: any = [];
for (let i = 0; i < 46; i++) {
data.push({
key: i,
name: `Edward King ${i}`,
age: 32,
address: `London, Park Lane no. ${i}`,
});
}
export default function QuoteModal() {
const [selectedRowKeys, setSelectedRowKeys] = useState([])
const [loading, setLoading] = useState(false)
// 批量操作加载中 效果
const start = () => {
setLoading(true)
// ajax request after empty completing
setTimeout(() => {
setSelectedRowKeys([])
setLoading(false)
}, 1000);
};
const onSelectChange = (selectedRowKeys: any) => {
setSelectedRowKeys(selectedRowKeys)
};
return (
<div>
<div style={{marginBottom: 16}}>
<Button type="primary" onClick={start} disabled={!(selectedRowKeys.length > 0)} loading={loading}>
批量下线
</Button>
<span style={{marginLeft: 8}}>
{selectedRowKeys.length > 0 ? `已选择 ${selectedRowKeys.length} 项` : ''}
</span>
</div>
<Table
rowSelection={{
selectedRowKeys,
onChange: onSelectChange,
}}
columns={columns}
dataSource={data}
pagination={{
pageSize: 5
}}
/>
</div>
);
}
二、可编辑单元格 表格 改为函数式组件
import React, {useContext, useEffect, useRef, useState} from 'react';
import {Button, Form, Input, Popconfirm, Table} from 'antd';
const EditableContext = React.createContext(null);
// 可编辑行
const EditableRow = ({index, ...props}) => {
const [form] = Form.useForm();
return (
<Form form={form} component={false}>
<EditableContext.Provider value={form}>
<tr {...props} />
</EditableContext.Provider>
</Form>
);
};
// 可编辑单元格
const EditableCell = ({
title,
editable,
children,
dataIndex,
record,
handleSave,
...restProps
}) => {
const [editing, setEditing] = useState(false);
const inputRef = useRef(null);
const form = useContext(EditableContext);
useEffect(() => {
if (editing) {
inputRef.current.focus();
}
}, [editing]);
const toggleEdit = () => {
setEditing(!editing);
form.setFieldsValue({
[dataIndex]: record[dataIndex],
});
};
const save = async () => {
try {
const values = await form.validateFields();
toggleEdit();
handleSave({...record, ...values});
} catch (errInfo) {
console.log('Save failed:', errInfo);
}
};
let childNode = children;
if (editable) {
childNode = editing ? (
<Form.Item
style={{
margin: 0,
}}
name={dataIndex}
rules={[
{
required: true,
message: `${title} is required.`,
},
]}
>
<Input ref={inputRef} onPressEnter={save} onBlur={save}/>
</Form.Item>
) : (
<div
className="editable-cell-value-wrap"
style={{
paddingRight: 24,
}}
onClick={toggleEdit}
>
{children}
</div>
);
}
return <td {...restProps}>{childNode}</td>;
};
export default function EditableTable() {
// 表格结构
const [columns, setCloumns] = useState([
{
title: 'name',
dataIndex: 'name',
width: '30%',
editable: true,
},
{
title: 'age',
dataIndex: 'age',
},
{
title: 'address',
dataIndex: 'address',
},
{
title: 'operation',
dataIndex: 'operation',
render: (_, record) =>
dataSource.length >= 1 ? (
<Popconfirm title="Sure to delete?" onConfirm={() => handleDelete(record.key)}>
<a>Delete</a>
</Popconfirm>
) : null,
},
])
// 模拟数据。可结合useEffect从后台数据库获取真实数据
const [dataSource, setDataSource] = useState([
{
key: '0',
name: 'Edward King 0',
age: '32',
address: 'London, Park Lane no. 0',
},
{
key: '1',
name: 'Edward King 1',
age: '32',
address: 'London, Park Lane no. 1',
},
])
// 行的数量
const [count, setCount] = useState(2)
// 删除行
const handleDelete = (key) => {
setDataSource(dataSource.filter((item) => item.key !== key))
};
// 新增行
const handleAdd = () => {
const newData = {
key: count,
name: `Edward King ${count}`,
age: '32',
address: `London, Park Lane no. ${count}`,
};
setDataSource([...dataSource, newData])
setCount(count + 1)
};
// 保存行
const handleSave = (row) => {
const newData = [...dataSource];
const index = newData.findIndex((item) => row.key === item.key);
const item = newData[index];
newData.splice(index, 1, {...item, ...row});
setDataSource(newData)
};
return (
<div>
<Button
onClick={handleAdd}
type="primary"
style={{
marginBottom: 16,
}}
>
新增一行
</Button>
<Table
components={{
body: {
row: EditableRow,
cell: EditableCell,
},
}}
rowClassName={() => 'editable-row'}
bordered
dataSource={dataSource}
columns={columns.map((col) => {
if (!col.editable) {
return col;
}
return {
...col,
onCell: (record) => ({
record,
editable: col.editable,
dataIndex: col.dataIndex,
title: col.title,
handleSave: handleSave,
}),
};
})}
/>
</div>
);
}