import React, { useState } from 'react';
import './App.css';
function TodoForm({addTodo}) {
const [value, setValue] = useState('');
const handleSubmit = e => {
e.preventDefault();
if(!value) return;
addTodo(value);
setValue('');
}
return <form onSubmit={handleSubmit}>
<input type='text' placeholder='add todo...' value={value} onChange={e=>setValue(e.target.value)}></input>
</form>
}
function Todo({todo, index, finishTodo, removeTodo}){
const handleComplete = e => {
finishTodo(index);
}
const handleDelete = e => {
removeTodo(index);
}
return (
<div style={{textDecoration: todo.isComplete?'line-through':''}}>
<div>
{todo.text}
<button onClick={handleComplete}>完成</button>
<button onClick={handleDelete}>删除</button>
</div>
</div>
)
}
function App() {
const [todos,setTodo] = useState([
{text: 'sleep', isComplete: false},
{text: 'eat', isComplete: true}
])
const addTodo = text => {
const todo = {text: text}
const newTodos = [...todos, todo];
setTodo(newTodos);
}
const finishTodo = index => {
const newTodos = [...todos];
newTodos[index].isComplete = true;
setTodo(newTodos);
}
const removeTodo = index => {
const newTodos = [...todos];
newTodos.splice(index, 1);
setTodo(newTodos);
}
return (
<div className="App">
<h1>todos</h1>
<div>
{
todos.map((todo, index) => {
return <Todo todo={todo} index={index} key={index} finishTodo={finishTodo} removeTodo={removeTodo}></Todo>
})
}
</div>
<TodoForm addTodo={addTodo}></TodoForm>
</div>
);
}
export default App;