react下类组件实现表格的行编写和单元格编写

这个是根据antd自己改装的 类组件实现表格的行编辑

import { Form, Input, InputNumber, Popconfirm, Table, Typography } from 'antd';
import React, { useState,Component } from 'react';
const originData = [];
for (let i = 0; i < 3; i++) {
  originData.push({
    key: i.toString(),
    name: `Edrward ${i}`,
    age: 32,
    address: `London Park no. ${i}`,
  });
}
const EditableCell = ({
  editing,
  dataIndex,
  title,
  inputType,
  record,
  index,
  children,
  ...restProps
}) => {
  const inputNode = inputType === 'number' ?  : ;
  return (
    
      {editing ? (
        
          {inputNode}
        
      ) : (
        children
      )}
    
  );
};
export default class App extends Component{
  state={
    data:originData,
    editingKey:'',
    load:false
  }
  // 是否编辑
  isEditing = record => record.key === this.state.editingKey;
  // 编辑
  edit = async (record) => {
    this.setState({
      editingKey:record.key
    })
    this.form.setFieldsValue({
      name: '',
      age: '',
      address: '',
      ...record,
    });

  };
  // 取消
  cancel = () => {
    this.setState({
      editingKey:''
    })
  };
  // 保存
  save = async (key) => {
    const {data} = this.state
    try {
      const row = await this.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,
        });
        this.setState({
          data:newData,
          editingKey:''
        })
      } else {
        newData.push(row);
        this.setState({
          data:newData,
          editingKey:''
        })
      }
      console.log(newData);
    } catch (errInfo) {
      console.log('Validate Failed:', errInfo);
    }
  };
   columns = [
    {
      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 {editingKey} = this.state
        let editable = this.isEditing(record);
        // 当 有key的时候 才能保存和取消
        return editable ? (
          
             this.save(record.key)}
              style={{
                marginRight: 8,
              }}
            >
              Save
            
            
              Cancel
            
          
        ) : (
           this.edit(record)}>
            Edit
          
        );
      },
    },
  ];

  render(){
    const {data,editingKey} = this.state
    const columns =  this.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: this.isEditing(record),
        }),
      };
    });
    return (
      
this.form=el} component={false}> ); } }

这个是根据antd改装的类组件实现单元格编辑

/** 表格单元格编辑  */
import { Button, Form, Input, Popconfirm, Table } from 'antd';
import React, { useContext, useEffect, useRef, useState,Component } from 'react';
const EditableContext = React.createContext(null);
const EditableRow = ({ index, ...props }) => {
  const [form] = Form.useForm();
  return (
    
); }; 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) { console.log(record); 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 ? ( ) : (
{children}
); } return
; }; export default class Test extends Component { state = { dataSource: [ { 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' } ], count: 2 }; // 删除操作 handleDelete = (key) => { const { dataSource } = this.state; const newData = dataSource.filter((item) => item.key !== key); this.setState({ dataSource: newData }); }; defaultColumns = [ { title: 'name', dataIndex: 'name', width: '30%', editable: true }, { title: 'num', dataIndex: 'age', editable: true }, { title: 'address', dataIndex: 'address', editable: true }, { title: '操作', dataIndex: 'operation', render: (_, record) => this.state.dataSource.length >= 1 ? ( <> this.handleDelete(record.key)}> Delete ) : null } ]; submit = (record)=>{ console.log(record); console.log(this.components.body.cell); } // 添加 handleAdd = () => { const { count, dataSource } = this.state; const newData = { key: count, name: `Edward King ${count}`, age: '32', address: `London, Park Lane no. ${count}` }; this.setState({ dataSource: [...dataSource, newData], count: count + 1 }); }; // 保存 handleSave = (row) => { console.log(row); const { dataSource } = this.state; const newData = [...dataSource]; const index = newData.findIndex((item) => row.key === item.key); const item = newData[index]; newData.splice(index, 1, { ...item, ...row }); this.setState({ dataSource: newData }); }; // 属性 components = { body: { row: EditableRow, cell: EditableCell } }; // 列 columns = this.defaultColumns.map((col) => { if (!col.editable) { return col; } console.log(col); return { ...col, onCell: (record) => ({ record, editable: col.editable, dataIndex: col.dataIndex, title: col.title, handleSave:this.handleSave }) }; }); render() { const { dataSource } = this.state; return (
{childNode}
'editable-row'} bordered dataSource={dataSource} columns={this.columns} /> ); } }

你可能感兴趣的:(react.js,前端)