react实现整个表格同时编辑

import { Table, InputNumber, Button } from 'antd';
import React from 'react';
const EditableContext = React.createContext();

class EditableCell extends React.Component {
 
  renderCell = () => {
    const {
      dataIndex,
      rowIndex,
      title,
      inputType,
      record,
      index,
      children,
      isEdit,
      data,
      ...restProps
    } = this.props;
    return (
      // 单元格判断
      
        {isEdit ? (
          // 这里可自行修改,项目需要数组输入框
             { return this.onChange(value,rowIndex,dataIndex )}} />
        ) : (
          children
        )}
      
    );
  };
  onChange = (value, rowIndex,dataIndex) => {
    // 表格变化走父组件方法
    this.props.handChange(value, rowIndex,dataIndex)
  };
  render() {
    return {this.renderCell};
  }
}

class EditableTable extends React.Component {
  constructor(props) {
    super(props);
    this.state = {  editingKey: '', isEdit: false, temData: [] };
    this.columns = [
      {
        title: 'name',
        dataIndex: 'name',
        width: '25%',
        editable: true,
      },
      {
        title: 'age',
        dataIndex: 'age',
        width: '20%',
        editable: true,
      },
    ];
  }

  handEdit() {
    this.setState({ isEdit: true });
  }
  handCancle() {
    this.setState({ isEdit: false });

  }
  handChange = (value, rowIndex,dataIndex) => {
    let otherData = JSON.parse(JSON.stringify(this.state.temData))
    otherData[rowIndex][dataIndex] = value
    this.setState({ temData:  JSON.parse(JSON.stringify(otherData))});
  }
  componentDidMount() {
    this.setState({ temData: JSON.parse(JSON.stringify(this.props.data)) });
    }

  render() {
    const components = {
      body: {
        cell: EditableCell,
      },
    };
    const columns = this.columns.map(col => {
      if (!col.editable) {
        return col;
      }
      return {
        ...col,
        onCell: (record, rowIndex) => ({
          record,
          rowIndex,
          dataIndex: col.dataIndex,
          title: col.title,
          isEdit: this.state.isEdit,
          data: this.props.data,
          handChange: this.handChange
        }),
      };
    });

    return (
        
{this.state.isEdit ? : } ); } } export default EditableTable

 

父组件通过绑定ref获取子组件修改后的表格

import EditTable from './components/EditTable'

function testPage() {
 const getData = () => {
    console.log(myRef)
  }
  let myRef = null;
  const data = [];
  for (let i = 0; i < 6; i++) {
    data.push({
      key: i.toString(),
      name: i,
      age: 32,
    });
  }
   return(
        (myRef = r)} data={data}>
      
   )
}

效果如下:

react实现整个表格同时编辑_第1张图片 

 点击编辑开启编辑模式

react实现整个表格同时编辑_第2张图片 

点击获取可看到temData值已经被修改,后续可自行进行操作 

react实现整个表格同时编辑_第3张图片 

 

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