首页 > 解决方案 > ReactJS:如何获取已更改的表行的数据

问题描述

我有一个维护表格状态的主要表格组件。我有一个愚蠢的组件,它从主要组件中获取道具。我用它来渲染表格行布局。我正在尝试使此表可编辑。出于这个原因,我需要一种方法来找出哪些tr被编辑了。有没有办法访问 trkey使用它可以访问整个对象?

标签: javascriptreactjs

解决方案


不,您无法获取子道具中键的值。从文档

键作为 React 的提示,但它们不会传递给您的组件。如果您需要在组件中使用相同的值,请将其作为具有不同名称的 prop 显式传递

const content = posts.map((post) =>
  <Post
    key={post.id}
    id={post.id}
    title={post.title} />
);

我头脑中的一个可能的解决方案可能如下:

import React from 'react';


class Table extends React.Component {


    constructor(props) {
        super(props);


        this.state = {
            rows: [
                {
                    id: 0,
                    title: "ABC"
                },
                {
                    id: 1,
                    title: "DEF"
                },
                {
                    id: 2,
                    title: "GHI"
                }
            ]
        }
    }

    render() {
        return <table>
            <tbody>

            {
                this.state.rows.map((item) => <Row key={item.id} item={item} updateItem={this.updateItem} />)
            }

            </tbody>
        </table>
    }

    updateItem = (newItemData) => {
        const index = this.state.rows.findIndex((r) => r.id == newItemData.id);

        let updatedRows = this.state.rows;

        updatedRows.splice(index, 1, newItemData);

        this.setState({
            rows: updatedRows
        });

    }
}


const Row = ({item, updateItem}) => {

    const [title, setValue] = React.useState(item.title);

    return <tr>
        <td>{item.id}</td>
        <td>
            <input type="text" value={title} onChange={(e) => setValue(e.currentTarget.value)} />
        </td>
        <td>
            <button onClick={() => updateItem({...item, title})}>Save</button>
        </td>
    </tr>
};

推荐阅读