react实现整个表格同时编辑

该文章展示了一个使用React和antd库创建的可编辑表格组件。组件包括EditableCell和EditableTable,支持切换编辑模式,以及在表格数据变化时调用父组件的方法进行更新。用户可以通过按钮控制编辑状态,并获取修改后的表格数据。
摘要由CSDN通过智能技术生成
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 (
      // 单元格判断
      <td {...restProps}>
        {isEdit ? (
          // 这里可自行修改,项目需要数组输入框
            <InputNumber defaultValue={data[rowIndex][dataIndex]} onChange={ (value)=> { return this.onChange(value,rowIndex,dataIndex )}} />
        ) : (
          children
        )}
      </td>
    );
  };
  onChange = (value, rowIndex,dataIndex) => {
    // 表格变化走父组件方法
    this.props.handChange(value, rowIndex,dataIndex)
  };
  render() {
    return <EditableContext.Consumer>{this.renderCell}</EditableContext.Consumer>;
  }
}

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 (
        <div>
        <Table
          components={components}
          bordered
          dataSource={this.props.data}
          columns={columns}
          rowClassName="editable-row"
          pagination={false}
        />
        {this.state.isEdit ?<Button  onClick={() => this.handCancle()}>取消</Button>
         :  <Button type="primary" onClick={() => this.handEdit()}>编辑</Button> }
        </div>
    );
  }
}
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(
       <EditTable ref={(r) => (myRef = r)} data={data}></EditTable>
      <button onClick={getData}>获取</button>
   )
}

效果如下:

 

 点击编辑开启编辑模式

 

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

 

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
React可以通过使用contentEditable属性来实现编辑表格。您可以使用React组件来创建表格,然后将contentEditable属性应用于表格单元格,以便用户可以编辑表格中的内容。您还可以使用React的状态来跟踪表格中的更改,并将这些更改保存到数据库或其他数据存储中。以下是一个简单的React组件,用于创建可编辑表格: ```javascript import React, { useState } from 'react'; function EditableTable() { const [tableData, setTableData] = useState([ { id: 1, name: 'John Doe', age: 30 }, { id: 2, name: 'Jane Smith', age: 25 }, { id: 3, name: 'Bob Johnson', age: 40 } ]); const handleCellChange = (id, field, value) => { const newData = tableData.map(row => { if (row.id === id) { return { ...row, [field]: value }; } return row; }); setTableData(newData); }; return ( <table> <thead> <tr> <th>ID</th> <th>Name</th> <th>Age</th> </tr> </thead> <tbody> {tableData.map(row => ( <tr key={row.id}> <td>{row.id}</td> <td contentEditable onBlur={e => handleCellChange(row.id, 'name', e.target.innerText)}>{row.name}</td> <td contentEditable onBlur={e => handleCellChange(row.id, 'age', e.target.innerText)}>{row.age}</td> </tr> ))} </tbody> </table> ); } export default EditableTable; ``` 在这个例子中,我们使用useState钩子来创建一个名为tableData的状态,它包含一个包含三个对象的数组,每个对象代表表格中的一行。我们还定义了一个名为handleCellChange的函数,该函数在单元格中的内容发生更改时被调用,并使用map函数更新tableData状态。最后,我们将contentEditable属性应用于表格单元格,并在失去焦点时调用handleCellChange函数来更新状态。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值