使用react hooks编写一个todo list
2021-07-27 本文已影响0人
mudssky
实现了添加todo和删除todo,还有用localStorage持久化的功能.
样式直接用的tailwind css 编写的,只用在className里面写类名,省事不少.
// import react from 'react'
import { useEffect, useState } from "react"
interface item{
key: string;
value: string;
}
export default function TodoList() {
const [inputValue, setInputValue] = useState('')
const [itemList, setItemList] = useState(Array<item>())
// 挂载时执行,载入itemList
useEffect(() => {
// effect
const todos=localStorage.getItem('todos')
if (todos) {
setItemList(JSON.parse(todos))
}
}, [])
// 更新时执行,保存todolist
useEffect(() => {
localStorage.setItem('todos',JSON.stringify(itemList))
}, [itemList])
return (
<div className="flex flex-col max-w-lg m-auto">
<h1 className='text-center'>TodoList</h1>
<div>
<input type="text" className="w-full ring-2 ring-blue-400 rounded-md outline-none mt-1 focus:ring-pink-300" id=""
onChange={(e) => { setInputValue(e.target.value) }}
value={inputValue}
onKeyDown={(e) => {
if (e.key === 'Enter') {
const newList = itemList.slice()
newList.push({key: new Date().getTime()+inputValue, value: inputValue })
setItemList(newList)
setInputValue('')
}}}
/>
</div>
<ul className="mt-2">{
itemList.map((i) =>
<div className="flex mt-2">
<li key={i.key} className="bg-blue-100 flex-auto">
{i.value}
</li>
<button className="w-1/12 bg-red-400" onClick={() => {
const newList = itemList.filter((x) => x !== i)
setItemList(newList)
}}>del</button>
</div>
)}
</ul>
</div>
)
}