Todo.tsx

  1. /* Todo.tsx */
  2. export interface IStateProps {
  3. id: number,
  4. text: string,
  5. isFinished: boolean
  6. }
  7. const Todo = () => {
  8. const [ todoList, setTodoList ] = useState<IStateProps[]>([]);
  9. const changeTodo = (id: number) => {
  10. const newTodoList = todoList.map(item => {
  11. if(item.id === id) {
  12. return Object.assign({}, item, {
  13. isFinished: !item.isFinished
  14. })
  15. }
  16. return item;
  17. });
  18. setTodoList(newTodoList);
  19. }
  20. const addTodo = (todo: IStateProps) => {
  21. setTodoList([...todoList, todo]);
  22. console.log(todoList)
  23. }
  24. return (
  25. <div className="todo">
  26. <TodoInput addTodo={addTodo} />
  27. <TodoList todoList={todoList} changeTodo={changeTodo} />
  28. </div>
  29. );
  30. }

TodoInput.tsx

  1. /* TodoInput.tsx */
  2. interface IPros {
  3. addTodo: (todo: IStateProps) => void;
  4. }
  5. const TodoInput = ({ addTodo }:IPros) => {
  6. const [ text, setText ] = useState('');
  7. const changeTextHandler = (e: React.ChangeEvent) => {
  8. setText((e.target as HTMLInputElement).value);
  9. }
  10. const addTodoHandler = () => {
  11. addTodo({
  12. id: new Date().getTime(),
  13. text: text,
  14. isFinished: false
  15. });
  16. setText('');
  17. }
  18. return (
  19. <div className="todo-input">
  20. <input type="text" placeholder="please input todolist" onChange={changeTextHandler} value={text} />
  21. <button onClick={addTodoHandler}>Add</button>
  22. </div>
  23. );
  24. }

TodoList.tsx

  1. /* TodoList.tsx */
  2. const style = {
  3. marginTop: '20px'
  4. }
  5. interface IPros {
  6. todoList: IStateProps[];
  7. changeTodo: (id: number) => void
  8. }
  9. const TodoList = ({ todoList, changeTodo }: IPros) => {
  10. const todolistdom = todoList.map(item => <TodoItem key={item.id} todo={item} changeTodo={changeTodo} />)
  11. return (
  12. <div className="todo-list" style={style}>
  13. { todolistdom }
  14. </div>
  15. );
  16. }

TodoItem.tsx

  1. /* TodoItem.tsx */
  2. const style = {
  3. marginTop: '5px',
  4. padding: '5px 0px',
  5. boxShadow:'0 0 3px #eee'
  6. }
  7. interface IPros {
  8. todo: IStateProps,
  9. changeTodo:(id:number) => void
  10. }
  11. const TodoItem = ({todo, changeTodo}: IPros) => {
  12. const changeHandler = () => {
  13. changeTodo(todo.id)
  14. }
  15. const spanStyle = {
  16. textDecoration: todo.isFinished ? 'line-through':'none'
  17. }
  18. return (
  19. <div className="todo-item" style={style}>
  20. <input type="checkbox" checked={todo.isFinished} onChange={changeHandler} />
  21. <span style={spanStyle}>{todo.text}</span>
  22. </div>
  23. );
  24. }

myapp.rar