mysql - React Ant Design 可编辑表

标签 mysql node.js reactjs rest antd

所以我跟进这个documentation用于创建可编辑行;这是 Ant Design 的 React CSS 库,我陷入了以下困境:

  • 如何将更改的行、newData[index] 传递给 onChange 事件?
  • 如何将一组数据更新到后端 REST API?我设法使用 Ant Design 的表单创建数据,但我不知道如何使用可编辑行更新它
  • 仅供引用,后端与 postman 完美配合:创建、更新、删除

  • 如何获取此代码的 ID?

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

我尝试将 id 替换为 ${id}${index}${products[index] } (使用模板文字)但它不起作用。

完整代码如下:

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;

更新: 所以我尝试将 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: '' });
      }
    });

它不会更新数据库中的数据。

最佳答案

有人可能仍然需要这个,antd table api .

您可以根据需要在列中传递带有一到三个参数的渲染键

function(text, record, index) {}

该列将如下所示:

const column = [{
                  dataIndex: "firstName",

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

关于mysql - React Ant Design 可编辑表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51719457/

相关文章:

javascript - 阻止 package.json 更新包

javascript - 如何使用 React 和 AXIOS 创建全局 Handler?

java - 在另一个 Activity 的 ListView 中显示结果 JSON 时出错

database - 我如何使用 node-orm2 通过 Express 为两个或多个数据库建模?

javascript - 在 node-mysql 中使用 SSH 隧道连接到 MySQL

javascript - 是否可以将 typescript 接口(interface)导出为方法的输出?

reactjs - 当子组件发生变化时如何重新渲染父组件?

node.js - React应用程序中的Socket io多个连接

c# - Entity Framework 6 MySQL 更改事务内的值

mysql查询类别和日期