如何在React.js中动态添加和删除表行 [英] How to add and remove table rows Dynamically in React.js
问题描述
my attempt fiddle here ..........
https://jsfiddle.net/techboy0007/j1eas924/
https://i.stack.imgur.com/KXFot.png
推荐答案
您可以通过使用react状态来实现.在您的情况下,您使用的是嵌套对象,因此在更新它们时需要小心.
You can achieve that by playing with react state. In your case you are using nested objects so you need to be carefully when you update them.
更改您的状态
并不是一个好主意,因为它很容易导致错误或意外行为.
It's not a good idea to mutate your state
because it can cause easily bugs or an unexpected behavior.
仔细查看处理
函数的工作方式.
Look closely how the handling
functions are working.
在这里,您将进行实时演示.
Here you have a live demo.
class App extends React.Component {
state = {
rows: []
};
handleChange = idx => e => {
const { name, value } = e.target;
const rows = [...this.state.rows];
rows[idx] = {
[name]: value
};
this.setState({
rows
});
};
handleAddRow = () => {
const item = {
name: "",
mobile: ""
};
this.setState({
rows: [...this.state.rows, item]
});
};
handleRemoveRow = () => {
this.setState({
rows: this.state.rows.slice(0, -1)
});
};
render() {
return (
<div>
<div className="container">
<div className="row clearfix">
<div className="col-md-12 column">
<table
className="table table-bordered table-hover"
id="tab_logic"
>
<thead>
<tr>
<th className="text-center"> # </th>
<th className="text-center"> Name </th>
<th className="text-center"> Mobile </th>
</tr>
</thead>
<tbody>
{this.state.rows.map((item, idx) => (
<tr id="addr0" key={idx}>
<td>{idx}</td>
<td>
<input
type="text"
name="name"
value={this.state.rows[idx].name}
onChange={this.handleChange(idx)}
className="form-control"
/>
</td>
<td>
<input
type="text"
name="mobile"
value={this.state.rows[idx].mobile}
onChange={this.handleChange(idx)}
className="form-control"
/>
</td>
</tr>
))}
</tbody>
</table>
<button
onClick={this.handleAddRow}
className="btn btn-default pull-left"
>
Add Row
</button>
<button
onClick={this.handleRemoveRow}
className="pull-right btn btn-default"
>
Delete Row
</button>
</div>
</div>
</div>
</div>
);
}
}
render(<App />, document.getElementById("root"));
PD:如果我能给您推荐的话,我想您需要进一步研究 react-javascript ,因为它将有助于更快地实现这样的目标,现在,您需要非常了解基础知识.
PD: If I can give you a recommendation I'd say that you need to study a little bit more about react - javascript to move forward because it would helpful to achieve things like this faster, right now you need to understand the basics pretty good.
这篇关于如何在React.js中动态添加和删除表行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!