简体   繁体   English

React Ant Design 可编辑表格

[英]React Ant Design editable table

so I follow up this documentation for creating a editable row;所以我按照这个文档来创建一个可编辑的行; It's a CSS library for React from Ant Design, I am stuck at the following:它是来自 Ant Design 的 React 的 CSS 库,我被困在以下方面:

  • How do I pass the changed row, the newData[index] to an onChange event?如何将更改后的行newData[index]传递给 onChange 事件?
  • How do I update a set of row of data to a back-end rest api?如何将一组数据行更新到后端休息 api? I managed to create data using form from Ant Design, but I don't know how to update it using editable row我设法使用 Ant Design 中的表单创建数据,但我不知道如何使用可编辑行更新它
  • Fyi, the back end works perfectly with postman: create, update, delete仅供参考,后端与邮递员完美配合:创建、更新、删除

  • How do I get the id of this code?我如何获得此代码的ID?

    axios.put("/api/product/update/:id"

I tried to replace the id with ${id} , ${index} , ${products[index]} (with template literal) but it doesn't work.我试图用${id}${index}${products[index]} (带有模板文字)替换id但它不起作用。

Here are the full code:以下是完整代码:

import React from 'react';
import axios from 'axios';
import { Table, Input, InputNumber, Popconfirm, Form } from 'antd';

const FormItem = Form.Item;
const EditableContext = React.createContext();

const EditableRow = ({ form, index, ...props }) => (
  <EditableContext.Provider value={form}>
    <tr {...props} />
  </EditableContext.Provider>
);

const EditableFormRow = Form.create()(EditableRow);

class EditableCell extends React.Component {
  getInput = () => {
    if (this.props.inputType === 'number') {
      return <InputNumber />;
    }
    return <Input />;
  };

  render() {
    const {
      editing,
      dataIndex,
      title,
      inputType,
      record,
      index,
      ...restProps
    } = this.props;
    return (
      <EditableContext.Consumer>
        {(form) => {
          const { getFieldDecorator } = form;
          return (
            <td {...restProps}>
              {editing ? (
                <FormItem style={{ margin: 0 }}>
                  {getFieldDecorator(dataIndex, {
                    rules: [{
                      required: true,
                      message: `Please Input ${title}!`,
                    }],
                    initialValue: record[dataIndex],
                  })(this.getInput())}
                </FormItem>
              ) : restProps.children}
            </td>
          );
        }}
      </EditableContext.Consumer>
    );
  }
}

class EditableTable extends React.Component {
  constructor(props) {
    super(props);
    this.state = { products: [], editingKey: '' };
    this.columns = [
      {
        title: 'Product Name',
        dataIndex: 'productname',
        width: '25%',
        editable: true,
      },
      {
        title: 'OS',
        dataIndex: 'os',
        width: '10%',
        editable: true,
      },
      {
        title: 'Category',
        dataIndex: 'category',
        width: '15%',
        editable: true,
      },
      {
        title: 'Model',
        dataIndex: 'model',
        width: '20%',
        editable: true,
      },
      {
        title: 'Serial Number',
        dataIndex: 'serialnumber',
        width: '20%',
        editable: true,
      },
      {
        title: 'Operation',
        dataIndex: 'operation',
        width: '10%',
        render: (text, record) => {
          const editable = this.isEditing(record);
          return (
            <div>
              {editable ? (
                <span>
                  <EditableContext.Consumer>
                    {form => (
                      <a
                        href="javascript:;"
                        onClick={() => this.save(form, record.id)}
                        style={{ marginRight: 8 }}
                      >
                        Save
                      </a>
                    )}
                  </EditableContext.Consumer>
                  <Popconfirm
                    title="Sure to cancel?"
                    onConfirm={() => this.cancel(record.id)}
                  >
                    <a>Cancel</a>
                  </Popconfirm>
                </span>
              ) : (
                  <a onClick={() => this.edit(record.id)}>Edit</a>
                )}
            </div>
          );
        },
      },
    ];
  }

  handleCategoryChange = event => { this.setState({ category: event.target.value }) }
  handleProductNameChange = event => { this.setState({ productname: event.target.value }) }
  handleOsNameChange = event => { this.setState({ os: event.target.value }) }
  handleModelchange = event => { this.setState({ model: event.target.value }) }
  handleSerialnumberChange = event => { this.setState({ serialnumber: event.target.value }) }
  handlePriceChange = event => { this.setState({ price: event.target.value }) }
  handleEquipmentChange = event => { this.setState({ equipment_condition: event.target.value }) }
  handleDetailChange = event => { this.setState({ detail: event.target.value }) }
  handleImageChange = event => { this.setState({ image: event.target.value }) }

  handleSubmit = event => {
    event.preventDefault();
    axios.put(`/api/product/update/:id`,
      {
        category: this.state.category,
        productname: this.state.productname,
        os: this.state.os,
        serialnumber: this.state.serialnumber,
        model: this.state.model,
        price: this.state.price,
        equipment_condition: this.state.equipment_condition,
        detail: this.state.detail,
        image: this.state.image
      })
  }

  componentDidMount() {
    axios.get('/api/product').then(res => {
    this.setState({ products: res.data });
    });
  }

  isEditing = (record) => {
    return record.id === this.state.editingKey;
  };

  edit(id) {
    console.log('products', this.state.products.id);
    // console.log('recordid', record.id);
    this.setState({ editingKey: id });
  }

  save(form, id) {
    console.log('key', id)
    form.validateFields((error, row) => {
      if (error) {
        return;
      }
      const newData = [...this.state.products];
      const index = newData.findIndex(item => id === item.id); 
      if (index > -1) {
        const item = newData[index];
        newData.splice(index, 1, { ...item, ...row, });      
        this.setState({ products: newData, editingKey: '' });
        console.log('newData', newData[index]) // data I want to update to API
        console.log('category', newData[index].category) // category

      } else {
        newData.push(this.state.products);
        this.setState({ products: newData, editingKey: '' });
      }
    });
  }

  cancel = () => {
    this.setState({ editingKey: '' });
  };

  render() {
    const components = {
      body: {
        row: EditableFormRow,
        cell: EditableCell,
      },
    };

    const columns = this.columns.map((col) => {
      if (!col.editable) {
        return col;
      }
      return {
        ...col,
        onCell: record => ({
          record,
          inputType: col.dataIndex === 'serialnumber' ? 'number' : 'text',
          dataIndex: col.dataIndex,
          title: col.title,
          editing: this.isEditing(record),
        }),
      };
    });

    return (
      <Table
        rowKey={this.state.id}
        components={components}
        bordered
        dataSource={this.state.products}
        columns={columns}
        rowClassName="editable-row"
      />
    );
  }
}

export default EditableTable;

Update: So I try put axios inside the save method, like so:更新:所以我尝试将 axios 放在 save 方法中,如下所示:

save(form, id) {
    form.validateFields((error, row) => {
      if (error) {
        return;
      }
      const newData = [...this.state.products];
      const index = newData.findIndex(item => id === item.id); 
      if (index > -1) {
        const item = newData[index];
        newData.splice(index, 1, { ...item, ...row, });      
        this.setState({ products: newData, editingKey: '' });
        console.log('newData', newData[index]) // data I want to update to API
        console.log('index', index) // index adalah index array
        console.log('id', id) // id adalah nomor index dalam tabel database, jangan sampai tertukar

        console.log('category', newData[index].category)
        console.log('productname', newData[index].productname)
        console.log('os', newData[index].os)
        console.log('serialnumber', newData[index].serialnumber)
        console.log('model', newData[index].model)
        console.log('detail', newData[index].detail)
        axios.put(`/api/product/update/:${id}`,
          {
            category: newData[index].category,
            productname: newData[index].productname,
            os: newData[index].os,
            serialnumber: newData[index].serialnumber,
            model: newData[index].model,
            price: newData[index].price,
            equipment_condition: newData[index].equipment_condition,
            detail: newData[index].detail,
            image: newData[index].image
          })

      } else {
        newData.push(this.state.products);
        this.setState({ products: newData, editingKey: '' });
      }
    });

It doesn't update the data on the database.它不会更新数据库中的数据。

Someone might still need this, The antd table api .有人可能仍然需要这个, antd table api

You can pass the render key in your column with one to three parameters depending on what you need您可以根据需要使用一到三个参数传递列中的渲染键

function(text, record, index) {}

The column will look like this:该列将如下所示:

const column = [{
                  dataIndex: "firstName",

                  render: (text, record, index) => console.log(text, record, index)
               }]

So there's this weird syntax that I have to remove from the url api.所以我必须从 url api 中删除这个奇怪的语法。 Pay attention to the very minor details of the url;注意 url 非常小的细节; I noticed it from the console log from the back end / node:我从后端/节点的控制台日志中注意到它:

axios.put(`/api/product/update/${id}`,
          {
            category: newData[index].category,
            productname: newData[index].productname,
            os: newData[index].os,
            serialnumber: newData[index].serialnumber,
            model: newData[index].model,
            price: newData[index].price,
            equipment_condition: newData[index].equipment_condition,
            detail: newData[index].detail,
            image: newData[index].image
          })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM