React的todolist的拆分项目
TodoList.jsx
import Todo from "./Todo"
export default function TodoList({ todos, toggleTodo, deleteTodo }) {
return <>
<ul>
{
todos.map(todo =>
<Todo key={todo.id} todo={todo} toggleTodo={toggleTodo} deleteTodo={deleteTodo} ></Todo>
)
}
</ul>
</>
}
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>,
)
NewItem.jsx
import { useEffect, useState } from "react"
export default function NewItem(props) {
const [curTodo, setCurTodo] = useState('')
function handleSumit(e) {
e.preventDefault()
if (curTodo.length === 0) return
props.onSumit(curTodo)
setCurTodo('')
}
return <>
<form onSubmit={handleSumit}>
<input type="text" value={curTodo} onChange={e => setCurTodo(e.target.value)} />
<button>Add</button>
</form>
</>
}
App.jsx
import { useEffect, useState } from "react"
import NewItem from './NewItem'
import TodoList from "./TodoList"
export default function App() {
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(title) {
setTodos(() =>
[
...todos,
{
id: crypto.randomUUID(),
title: title,
status: false
}
]
)
}
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 (
<>
<NewItem onSumit={addTodo}></NewItem>
<TodoList todos={todos} toggleTodo={toggleTodo} deleteTodo={deleteTodo}></TodoList>
</>
)
}
Todo.jsx
export default function Todo({ todo, toggleTodo, deleteTodo }) {
return <>
<li>
<label>
<input
type="checkbox"
checked={todo.status}
onChange={(e) => toggleTodo(todo.id, e.target.checked)}
/>
<span className={todo.status ? "underline" : ''}>{todo.title}</span>
</label>
<button onClick={() => deleteTodo(todo.id)}>Delete</button>
</li>
</>
}
标签:function,return,todolist,react,拆分,import,todo,id,todos
From: https://www.cnblogs.com/zhuoss/p/17720978.html