javascript - ReactJS:如何获取已更改的表行的数据
问题描述
我有一个维护表格状态的主要表格组件。我有一个愚蠢的组件,它从主要组件中获取道具。我用它来渲染表格行布局。我正在尝试使此表可编辑。出于这个原因,我需要一种方法来找出哪些tr
被编辑了。有没有办法访问 trkey
使用它可以访问整个对象?
解决方案
不,您无法获取子道具中键的值。从文档:
键作为 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>
};
推荐阅读
- timestamp - 有没有办法在 Apache Phoenix 中使用 TIME ZONE 信息来更新 TIMESTAMP?
- c - C、传值,在Linux中
- optimization - 如何查看llvm优化前后的差异 Selectiondag
- php - 在单独的进程中运行测试时,PHPUnit 无法生成代码覆盖率
- json - 通过 Ecvel 使用 Hayperlink Funktion 发送 JSON 有效负载 - 问题
- android - 导入项目时无法点击完成按钮
- r - 如何叠加两个具有相同尺寸的数据框,将值粘贴到相应的单元格中?
- python - Pandas - 将数据附加到数据框会导致比文件源更多的行
- python - Snakemake 在开始下一个并行作业之前等待完成所有并行作业
- php - 警告:PHP 中未定义的数组键错误