这里不涉及声明周期,所以只是用到了useState:
/*
* @Descripttion:
* @version:
* @Author: ZhangJunQing
* @Date: 2022-03-07 16:19:28
* @LastEditors: ZhangJunQing
* @LastEditTime: 2022-03-10 14:24:56
*/
import React, {
useState } from 'react'
const TodoList = () => {
let [name, setName] = useState('')
let [age, setAge] = useState('')
let [habby, setHabby] = useState('')
let [dataList, setDateList] = useState([])
const changeInput = (set, value) => {
if (value.target) {
set(_ => value.target.value)
} else {
set(_ => value)
}
}
// 新增列表
// name唯一标识
const add = () => {
if (dataList.find(i => i.name === name)) {
alert("姓名重复!")
return false
}
setDateList(list => [...list, {
name, age, habby }])
// 清空默认值
setName("")
setAge("")
setHabby("")
}
// 删除
const del=(name)=>{
setDateList(list=>list.filter(i=>name!==i.name))
}
return (
<div style={
{
marginTop: "20px" }}>
<div style={
{
marginBottom: "20px" }}>
姓名:<input value={
name} onChange={
(e) => {
changeInput(setName, e.target.value) }} /> <br />
</div>
<div style={
{
marginBottom: "20px" }}>
年龄:<input value={
age} onChange={
(e) => {
changeInput(setAge, e.target.value) }} /> <br />
</div>
<div style={
{
marginBottom: "20px" }}>
爱好:<input value={
habby} onChange={
(e) => {
changeInput(setHabby, e.target.value) }} /> <br />
</div>
<button onClick={
add}>新增</button>
<table style={
{
border: "1px solid red", width: "300px", marginTop: "20px" }}>
<thead>
<tr>
<th>姓名</th>
<th>年龄</th>
<th>爱好</th>
<th>操作</th>
</tr>
</thead>
<tbody>
{
dataList.map(i => {
return (
<tr key={
i.name}>
<th>{
i.name}</th>
<th>{
i.age}</th>
<th>{
i.habby}</th>
<th style={
{
color:"orange"}} onClick={
()=>{
del(i.name)}}>删除</th>
</tr>
)
})}
</tbody>
</table>
</div>
)
}
export default TodoList