Todo.tsx
/* Todo.tsx */
export interface IStateProps {
id: number,
text: string,
isFinished: boolean
}
const Todo = () => {
const [ todoList, setTodoList ] = useState<IStateProps[]>([]);
const changeTodo = (id: number) => {
const newTodoList = todoList.map(item => {
if(item.id === id) {
return Object.assign({}, item, {
isFinished: !item.isFinished
})
}
return item;
});
setTodoList(newTodoList);
}
const addTodo = (todo: IStateProps) => {
setTodoList([...todoList, todo]);
console.log(todoList)
}
return (
<div className="todo">
<TodoInput addTodo={addTodo} />
<TodoList todoList={todoList} changeTodo={changeTodo} />
</div>
);
}
TodoInput.tsx
/* TodoInput.tsx */
interface IPros {
addTodo: (todo: IStateProps) => void;
}
const TodoInput = ({ addTodo }:IPros) => {
const [ text, setText ] = useState('');
const changeTextHandler = (e: React.ChangeEvent) => {
setText((e.target as HTMLInputElement).value);
}
const addTodoHandler = () => {
addTodo({
id: new Date().getTime(),
text: text,
isFinished: false
});
setText('');
}
return (
<div className="todo-input">
<input type="text" placeholder="please input todolist" onChange={changeTextHandler} value={text} />
<button onClick={addTodoHandler}>Add</button>
</div>
);
}
TodoList.tsx
/* TodoList.tsx */
const style = {
marginTop: '20px'
}
interface IPros {
todoList: IStateProps[];
changeTodo: (id: number) => void
}
const TodoList = ({ todoList, changeTodo }: IPros) => {
const todolistdom = todoList.map(item => <TodoItem key={item.id} todo={item} changeTodo={changeTodo} />)
return (
<div className="todo-list" style={style}>
{ todolistdom }
</div>
);
}
TodoItem.tsx
/* TodoItem.tsx */
const style = {
marginTop: '5px',
padding: '5px 0px',
boxShadow:'0 0 3px #eee'
}
interface IPros {
todo: IStateProps,
changeTodo:(id:number) => void
}
const TodoItem = ({todo, changeTodo}: IPros) => {
const changeHandler = () => {
changeTodo(todo.id)
}
const spanStyle = {
textDecoration: todo.isFinished ? 'line-through':'none'
}
return (
<div className="todo-item" style={style}>
<input type="checkbox" checked={todo.isFinished} onChange={changeHandler} />
<span style={spanStyle}>{todo.text}</span>
</div>
);
}
myapp.rar