You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React新手求助:表格批量新增3条记录及整行删除问题

Hey Alex, let's get your React table sorted out with batch additions and row deletions. I’ll walk you through fixing the single-field input issue, adding the missing components, and implementing the features you need.

Problem Breakdown

From your description, we need to tackle these key points:

  • Replace single-field input with full-row data entry
  • Add a button to batch insert 3 empty records
  • Implement row-by-row deletion
  • Ensure fetched data loads and displays correctly
Modified Complete Code
import React, { Component } from 'react';

class Table extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [], // Stores the fetched and added records
    };
  }

  // Fetch data when component mounts
  componentDidMount() {
    // Replace with your actual API endpoint
    fetch('your-api-endpoint-here')
      .then(response => response.json())
      .then(fetchedData => {
        this.setState({ data: fetchedData });
      })
      .catch(error => {
        console.error('Error fetching data:', error);
      });
  }

  // Update specific field in a row
  handleInputChange = (index, field, value) => {
    const updatedData = [...this.state.data];
    updatedData[index][field] = value;
    this.setState({ data: updatedData });
  };

  // Batch add 3 empty records
  handleBatchAdd = () => {
    const newRecords = Array(3).fill(null).map(() => ({
      // Adjust fields to match your table's actual structure
      id: Date.now() + Math.random(), // Unique temporary ID
      name: '',
      age: '',
      email: ''
    }));
    this.setState(prevState => ({
      data: [...prevState.data, ...newRecords]
    }));
  };

  // Delete a specific row
  handleDeleteRow = (index) => {
    const updatedData = this.state.data.filter((_, i) => i !== index);
    this.setState({ data: updatedData });
  };

  render() {
    // Define your table columns (match your data structure)
    const columns = ['Name', 'Age', 'Email', 'Actions'];

    return (
      <div className="table-container">
        <button onClick={this.handleBatchAdd} style={{ marginBottom: '10px' }}>
          Batch Add 3 Records
        </button>
        <table border="1" cellPadding="8" cellSpacing="0">
          <thead>
            <tr>
              {columns.map(col => (
                <th key={col}>{col}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {this.state.data.map((row, index) => (
              <tr key={row.id || index}>
                <td>
                  <input
                    type="text"
                    value={row.name || ''}
                    onChange={(e) => this.handleInputChange(index, 'name', e.target.value)}
                    placeholder="Enter name"
                  />
                </td>
                <td>
                  <input
                    type="number"
                    value={row.age || ''}
                    onChange={(e) => this.handleInputChange(index, 'age', e.target.value)}
                    placeholder="Enter age"
                  />
                </td>
                <td>
                  <input
                    type="email"
                    value={row.email || ''}
                    onChange={(e) => this.handleInputChange(index, 'email', e.target.value)}
                    placeholder="Enter email"
                  />
                </td>
                <td>
                  <button onClick={() => this.handleDeleteRow(index)} style={{ color: 'red' }}>
                    Delete
                  </button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    );
  }
}

export default Table;
Key Feature Explanations
  • Data Fetching: The componentDidMount method uses fetch to pull your data — just swap the placeholder URL with your actual API endpoint. We added error handling so you can debug if the request fails.
  • Batch Addition: handleBatchAdd creates 3 empty records with unique temporary IDs (tweak the fields to match your table's needs) and appends them to the existing data state.
  • Row Deletion: handleDeleteRow filters out the row at the clicked index, updating the state to remove that record from the table instantly.
  • Field Updates: handleInputChange targets a specific row and field, updating only that part of the state to keep user input in sync with your data.
  • Dynamic Rendering: Headers and rows render dynamically based on your column and data structure, so you can easily add/remove fields later without rewriting the whole table.

Just adjust the field names (like name, age, email) to match the data returned by your GET request, and you’re ready to go!

内容的提问来源于stack exchange,提问作者Alex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:49:07