在 Ant Design 的 Table 中嵌入输入框,可以使用 Table 的 render 属性来自定义每个单元格的内容。在 render 函数中,可以返回一个包含输入框的 React 组件。

以下是一个示例代码:

import React, { useState } from 'react';
import { Table, Input } from 'antd';

const data = [
  { id: 1, name: 'John Doe', age: 25 },
  { id: 2, name: 'Jane Smith', age: 30 },
];

const EditableCell = ({ editable, value, onChange }) => (
  <div>
    {editable ? (
      <Input value={value} onChange={e => onChange(e.target.value)} />
    ) : (
      value
    )}
  </div>
);

const App = () => {
  const [dataSource, setDataSource] = useState(data);

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: 'Name',
      dataIndex: 'name',
      key: 'name',
      render: (text, record) => (
        <EditableCell
          editable={record.editable}
          value={text}
          onChange={value => handleInputChange(value, record.key, 'name')}
        />
      ),
    },
    {
      title: 'Age',
      dataIndex: 'age',
      key: 'age',
      render: (text, record) => (
        <EditableCell
          editable={record.editable}
          value={text}
          onChange={value => handleInputChange(value, record.key, 'age')}
        />
      ),
    },
  ];

  const handleInputChange = (value, key, dataIndex) => {
    const updatedData = dataSource.map(item => {
      if (item.key === key) {
        return { ...item, [dataIndex]: value };
      }
      return item;
    });
    setDataSource(updatedData);
  };

  return <Table dataSource={dataSource} columns={columns} />;
};

export default App;

在上面的代码中,我们定义了一个名为 EditableCell 的组件,它接收 editable、value 和 onChange 作为 props。如果 editable 为 true,则渲染一个 Input 组件,否则渲染 value。在 Table 的 columns 中,我们使用 EditableCell 组件来渲染每个单元格的内容,并通过 onChange 回调函数来更新数据源中的值。

在 App 组件中,我们使用 useState 来维护数据源的状态,并在 handleInputChange 函数中更新数据源的值。最后,我们将数据源和列配置传递给 Table 组件来渲染表格。

注意:上述示例中使用了 React 的 Hooks API,所以需要确保你的项目中已经安装了 React 的版本 16.8.0 或更高版本。

Ant Design Table 中嵌入可编辑输入框:实现数据实时更新

原文地址: https://www.cveoy.top/t/topic/QSr 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录