【发布时间】:2020-09-30 05:50:43
【问题描述】:
我根据表单给出的输入渲染了表格,我关心的是使表格行可编辑并且在编辑时,我的意思是 onChange() 名称应该存储在 this.state 中。
这是我的 App.js 文件,
import React, { Component } from "react";
import Form from "./Form";
export default class App extends Component {
state = {
names: [
/*
Object structure
{id: 1,name:'Aashiq'}
*/
]
};
handleNameChange(e) {
this.setState(
{
names: { ...this.state.names, name: e.target.value }
},
console.log(this.state.names)
);
}
renderTable() {
return this.state.names
.sort((a, b) => a.id - b.id)
.map((eachName) => {
const { id, name } = eachName;
return (
<tr key={id}>
<td>{id}</td>
<td onChange={(e) => this.handleNameChange(e)}>
<div contentEditable>{name}</div>{" "}
</td>
<td>
<input
type="button"
value="Delete"
onClick={() => this.deleteName(eachName.id)}
/>
</td>
</tr>
);
});
}
deleteName = (id) => {
this.state.names &&
this.setState({
names: this.state.names.filter((name) => name.id !== id)
});
};
addName = (newName) => {
this.setState((currentState) => {
const newNames = [...currentState.names];
newNames.push(newName);
return {
names: newNames
};
});
};
render() {
return (
<>
<Form onSubmit={this.addName} names={this.state.names} />
<br />
<table id="details">
<tbody>
<tr>
<th>ID</th>
<th>Names</th>
<th>Operation</th>
</tr>
{this.renderTable()}
</tbody>
</table>
</>
);
}
}
你可以在这里看到,我尝试在 div 中使用 contentEditable 属性,但它没有反映使用任何处理程序函数,所以有人提出解决方案会很好,顺便说一句,我只需要编辑名称字段。
【问题讨论】:
-
只需在
中输入一个输入,然后像往常一样处理输入。 它如何告诉用户内容是可编辑的?我的建议是使用标准输入,它可能会在悬停时显示其边框,然后用户可以根据需要单击并编辑您的意思是在单击按钮时启用和禁用输入字段是@Chiranjib,我想在操作栏中有一个编辑按钮来处理数据,你能根据这个上下文给出建议吗?已经发布了一个答案,很粗略但应该能让你继续前进
标签: javascript reactjs html-table