React的todolist
src/main.jsx
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App.jsx'
import './index.css'
ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
<App />
</React.StrictMode>,
)
src/App.jsx
import { useEffect, useState } from "react"
export default function App() {
const [curTodo, setCurTodo] = useState('')
const [todos, setTodos] = useState(() => {
const localValue = localStorage.getItem("ITEMS")
if (localValue == null) return []
return JSON.parse(localValue)
})
useEffect(() => {
localStorage.setItem("ITEMS", JSON.stringify(todos))
}, [todos])
function addTodo(e) {
e.preventDefault()
if (curTodo.length === 0) return
setTodos(() =>
[
...todos,
{
id: crypto.randomUUID(),
title: curTodo,
status: false
}
]
)
setCurTodo('')
}
function toggleTodo(id, status) {
setTodos(() =>
todos.map(todo => {
if (todo.id === id) {
return { ...todo, status }
}
return todo
})
)
}
function deleteTodo(id) {
setTodos(() =>
// 符合这个条件(todo.id !== id)的元素,都会被过滤下来,并将这些元素组成一个数组返回
todos.filter(todo => todo.id !== id)
)
}
return (
<>
<form onSubmit={addTodo}>
<input type="text" value={curTodo} onChange={e => setCurTodo(e.target.value)} />
<button>Add</button>
</form>
<ul>
{
todos.map(todo =>
<li key={todo.id}>
<label>
<input
type="checkbox"
checked={todo.status}
onChange={(e) => toggleTodo(todo.id, e.target.checked)}
/>
{todo.title}
</label>
<button onClick={() => deleteTodo(todo.id)}>Delete</button>
</li>
)
}
</ul>
</>
)
}
标签:return,todolist,react,import,todo,id,todos
From: https://www.cnblogs.com/zhuoss/p/17720975.html