简单实现TODOList
实现新增和列表展示
- 使用map循环展示列表
- 使用useState
- 实现input的双向绑定
- 使用onClick绑定点击事件
import React, { useState } from "react";
function TodoList() {
const [inputValue, setInputValue] = useState('')
const [todoList, setTodoList] = useState([])
const handleClick = () => {
setTodoList([...todoList, inputValue])
setInputValue('')
}
return (
<>
<div>
<input
value={inputValue}
onChange={e => setInputValue(e.target.value)}
/>
<button onClick={handleClick}>提交</button>
</div>
<ul>
{
todoList.map((item, index) => {
return <li key={index}>{item}</li>
})
}
</ul>
</>
)
}
export default TodoList
实现删除功能
在li标签增加handleDelete方法
import React, { useState } from "react";
function TodoList() {
const [inputValue, setInputValue] = useState('')
const [todoList, setTodoList] = useState([])
const handleClick = () => {
setTodoList([...todoList, inputValue])
setInputValue('')
}
const handleDelete = index => {
const list = todoList.filter((item, i) => i !== index)
setTodoList(list)
}
return (
<>
<div>
<input
value={inputValue}
onChange={e => setInputValue(e.target.value)}
/>
<button onClick={handleClick}>提交</button>
</div>
<ul>
{
todoList.map((item, index) => {
return <li key={index} onClick={handleDelete(index)}>{item}</li>
})
}
</ul>
</>
)
}
export default TodoList
但是发现这样写,每次点击提交按钮时,这个TODO就同步被删除了。查询后发现问题出现在
onClick={handleDelete(index)}这里,由于之前使用的都是vue,所以习惯的使用了这种方式去传参,但是在react中,onClick事件应该接收一个函数引用而不是函数调用。如之前那样写,在渲染时会直接执行删除方法删除TODO。
正确写法:
- 使用箭头函数
onClick={() => handleDelete(index)}
- 使用bind方法
onClick={handleDelete.bind(this, index)}
完整代码:
import React, { useState } from "react";
function TodoList() {
const [inputValue, setInputValue] = useState('')
const [todoList, setTodoList] = useState([])
const handleClick = () => {
setTodoList([...todoList, inputValue])
setInputValue('')
}
const handleDelete = index => {
const list = todoList.filter((item, i) => i !== index)
setTodoList(list)
}
return (
<>
<div>
<input
value={inputValue}
onChange={e => setInputValue(e.target.value)}
/>
<button onClick={handleClick}>提交</button>
</div>
<ul>
{
todoList.map((item, index) => {
return <li key={index} onClick={() => handleDelete(index)}>{item}</li>
})
}
</ul>
</>
)
}
export default TodoList