首页 > 解决方案 > 如何添加添加行按钮 React?

问题描述

我是一名初学者 Web 开发人员,我有一个使用 JSON 数据的 React 表格​​代码,请告诉我如何实现,以便“单击按钮时创建新行”

应用程序.js

import React, { Component } from 'react';
import './App.css';
import StaffTable from './components/staff-table'
import data from './data/staff.json'


class App extends Component {
  render() {
    return (
      <div className="App">
       <h1><StaffTable  data={data} /></h1>
      </div>

    );
  }
}


export default App;

索引.jsx

import React from 'react'

export default function StaffTable(props) {
    return (
        <div>
        <table>

            <thead>

                <tr>
                    <th>#</th>
                    <th>name</th>
                    <th>age</th>
                    <th>number</th>

                </tr>
            </thead>
            <tbody>

                {
                props.data.map(row =>(
                    <tr>
                        <td>{row.id}</td>
                        <td>{row.name}</td>
                        <td>{row.age}</td>
                        <td>{row.number}</td>
                        <td><button className="editRow">Edit</button></td>
                    </tr>

                ))
                }

            </tbody>
        </table>
        <button className="addRow" >State</button>
        </div>
    )

}

员工.json

[

        {
            "id": 1,
            "name": "Alex",
            "age": "18",
            "number": "00000"
        },
        {
            "id": 2,
            "name": "Anton",
            "age": "20",
            "number": "11111"
        },
        {
            "id": 3,
            "name": "Bob",
            "age": "22",
            "number": "22222"
        },
        {
            "id": 4,
            "name": "Ivan",
            "age": "25",
            "number": "33333"
        },
        {
            "id": 5,
            "name": "Jack",
            "age": "28",
            "number": "44444"
        },
        {
            "id": 6,
            "name": "Maria",
            "age": "30",
            "number": "55555"
        },
        {
            "id": 7,
            "name": "Viktoria",
            "age": "32",
            "number": "66666"
        }           

]

标签: javascriptjsonreactjs

解决方案


我会创建一个“行”组件和一个“行”组件。这两个都将存储在您的“应用程序”组件中。你的“app”组件应该有一个数据数组(在它的状态下)你传递给“rows”组件。

单击添加新按钮将调用应用程序组件中的一个函数,该函数将一行添加到应用程序组件状态的数组中。


推荐阅读