React + TS todolist demo

TodoList

import React, { useState } from "react";
import TodoItem from "./TodoItem";

interface TodoList {
  inputValue: string;
  list: string[];
}

const defaultTodoList: TodoList = {
  inputValue: "",
  list: [],
};

interface Props {}

const TodoListDemo: React.FC = (props) => {
  const [todo, setTodo] = useState(defaultTodoList);

  const handleBtnClick = () => {
    setTodo((preTodo) => ({
      inputValue: "",
      list: [...preTodo.list, preTodo.inputValue],
    }));
  };

  // 因为在handleItemDelete里面有setTodo方法,todo是定义在TodoList这个文件中的
  // 所以删除方法一定写在TodoList文件中,但是绑定这个函数的组件在TodoItem当中,所以
  const handleItemDelete = (index) => {
    setTodo((preTodo) => {
      const list = [...preTodo.list];
      list.splice(index, 1);
      return {
        inputValue: preTodo.inputValue,
        list,
      };
    });
  };

  const getTodoItem = () => {
    return todo.list.map((item, index) => {
      return (
        
      );
    });
  };

  return (
    <>
      
setTodo({ ...todo, inputValue: e.target.value })} />
    {getTodoItem()}
); }; export default TodoListDemo;

TodoItem

import React from "react";

interface TodoItemProps {
  content: string;
  index: number;
  deleteItem: (index: any) => void;
}

const TodoItem: React.FC = (props) => {
  const { content, index, deleteItem } = props;
  return 
  • deleteItem(index)}>{content}
  • ; }; export default TodoItem;

    传递的 props 也可以直接在括号中写对象

    import React from "react";
    
    interface Props {
      content: string;
      index: number;
      deleteItem: (index: any) => void;
    }
    
    const TodoItem: React.FC = ({ content, index, deleteItem }) => {
      return 
  • deleteItem(index)}>{content}
  • ; }; export default TodoItem;

    你可能感兴趣的:(React + TS todolist demo)