<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="https://cdn.staticfile.org/react/16.4.0/umd/react.development.js"></script>
<script src="https://cdn.staticfile.org/react-dom/16.4.0/umd/react-dom.development.js"></script>
<script src="https://cdn.staticfile.org/babel-standalone/6.26.0/babel.min.js"></script>
</head>
<body>
<div id="test"></div>
<script type="text/babel">
class MyComponent extends React.Component{
state = {
obj:[
{id:1,name:"张三",age:18},
{id:2,name:"李四",age:18},
{id:3,name:"王五",age:18}
]
}
btn=()=>{
if(this.refs.name.value!=''&&this.refs.age.value!=''){
this.setState({
obj:[...this.state.obj,{id:this.state.obj.length+1,name:this.refs.name.value,age:this.refs.age.value}]
})
alert("添加成功!")
}else{
alert("请输入内容!")
}
this.refs.name.value =''
this.refs.age.value =''
}
del(i){
console.log(i)
var obj=this.state.obj
if(confirm("当前条此内容将被删除!")){
obj.splice(i,1)
this.setState({
obj:obj
})
}
}
render(){
return(
<div>
姓名:<input type="text" ref="name"/>
年龄:<input type="text" ref="age"/>-
<button onClick={this.btn}>添加</button> <br/><br/>
<table border="1px" width="500">
<thead align="center">
<tr>
<th>id</th>
<th>姓名</th>
<th>年龄</th>
<th>操作</th>
</tr>
</thead>
<tbody>
{
this.state.obj.map((item,i)=>{
return <tr key={i} align="center">
<td>{item.id}</td>
<td>{item.name}</td>
<td>{item.age}</td>
<td><button onClick={this.del.bind(this,i)}>删除</button></td>
</tr>
})
}
</tbody>
</table>
</div>
)
}
}
ReactDOM.render(<MyComponent />,document.querySelector('#test'))
</script>
</body>
</html>
react增删表格简单
最新推荐文章于 2024-07-27 21:32:52 发布
这个博客展示了如何使用React创建一个简单的表格,允许用户添加和删除行。通过定义一个React组件,设置状态来存储表格数据,并使用内联事件处理函数进行交互。用户输入姓名和年龄,点击添加按钮将新数据添加到表格中,点击删除按钮会弹窗确认并移除对应行。
5869

被折叠的 条评论
为什么被折叠?



