在软件开发中,有时我们需要对数据表格中的某些列进行保护,使其不可编辑,而其他列仍然可以编辑。这种需求在各种应用场景中都很常见,例如在后台管理系统中,某些敏感字段(如ID、创建时间等)通常不允许用户修改。
假设我们使用React和一个表格组件库(如Ant Design),可以通过以下步骤实现:
import React from 'react';
import { Table, Input } from 'antd';
const EditableCell = ({
editing,
dataIndex,
title,
inputType,
record,
index,
children,
...restProps
}) => {
const inputNode = inputType === 'number' ? <Input.Number /> : <Input />;
return (
<td {...restProps}>
{editing ? (
<form.Item
name={dataIndex}
style={{
margin: 0,
}}
rules={[
{
required: true,
message: `请输入 ${title}!`,
},
]}
>
{inputNode}
</form.Item>
) : (
children
)}
</td>
);
};
const EditableTable = () => {
const [form] = Form.useForm();
const [data, setData] = useState([]);
const [editingKey, setEditingKey] = useState('');
const isEditing = (record) => record.key === editingKey;
const edit = (record) => {
form.setFieldsValue({
name: '',
age: '',
address: '',
...record,
});
setEditingKey(record.key);
};
const cancel = () => {
setEditingKey('');
};
const save = async (key) => {
try {
const row = await form.validateFields();
const newData = [...data];
const index = newData.findIndex((item) => key === item.key);
if (index > -1) {
const item = newData[index];
newData.splice(index, 1, { ...item, ...row });
setData(newData);
setEditingKey('');
} else {
newData.push(row);
setData(newData);
setEditingKey('');
}
} catch (errInfo) {
console.log('Validate Failed:', errInfo);
}
};
const columns = [
{
title: 'ID',
dataIndex: 'id',
width: '10%',
editable: false, // 设置此列不可编辑
},
{
title: 'name',
dataIndex: 'name',
width: '25%',
editable: true,
},
{
title: 'age',
dataIndex: 'age',
width: '15%',
editable: true,
},
{
title: 'address',
dataIndex: 'address',
width: '40%',
editable: true,
},
{
title: 'operation',
dataIndex: 'operation',
render: (_, record) => {
const editable = isEditing(record);
return editable ? (
<span>
<a
href="javascript:void(0)"
onClick={() => save(record.key)}
style={{
marginRight: 8,
}}
>
Save
</a>
<a onClick={cancel}>Cancel</a>
</span>
) : (
<a disabled={editingKey !== ''} onClick={() => edit(record)}>
Edit
</a>
);
},
},
];
const mergedColumns = columns.map((col) => {
if (!col.editable) {
return col;
}
return {
...col,
onCell: (record) => ({
record,
inputType: col.dataIndex === 'age' ? 'number' : 'text',
dataIndex: col.dataIndex,
title: col.title,
editing: isEditing(record),
}),
};
});
return (
<Form form={form} component={false}>
<Table
components={{
body: {
cell: EditableCell,
},
}}
bordered
dataSource={data}
columns={mergedColumns}
rowClassName="editable-row"
pagination={{
onChange: cancel,
}}
/>
</Form>
);
};
export default EditableTable;
如果在实现过程中遇到列不可编辑的问题,可以检查以下几点:
editable
属性设置正确:在列定义中明确指定哪些列不可编辑。通过上述方法,可以有效地控制表格中某些列的可编辑性,从而提升应用的安全性和用户体验。
没有搜到相关的文章