index.tsx
import { useState, memo, useEffect } from "react";
import Tdinput from "./tdinput";
import TdItem from "./toitem";
import { i_listitem } from "../interfaces";
function Home() {
let [todoList, settodoList] = useState<i_listitem[]>([]);
useEffect(() => {
settodoList(JSON.parse(localStorage.getItem("todolist") || "[]"));
}, []);
useEffect(() => {
localStorage.setItem("todolist", JSON.stringify(todoList));
}, [todoList]);
const addItem = (value: string) => {
if (!value) {
return alert("请输入数据");
}
let obj: i_listitem = {
id: Date.now(),
content: value,
status: false,
};
settodoList([obj, ...todoList]);
};
const changeStatu = (id: number) => {
let newTodolist = todoList.map((item) => {
if (item.id === id) {
item.status = !item.status;
}
return item;
});
settodoList(newTodolist);
};
const delItem = (id: number) => {
settodoList(
todoList.filter((item) => {
return item.id !== id;
})
);
};
return (
<div>
<Tdinput addItem={addItem} />
{todoList.map((item) => {
return (
<TdItem
changeStatu={changeStatu}
delItem={delItem}
item={item}
key={item.id}
/>
);
})}
</div>
);
}
export default memo(Home);
input.tsx
绑定的方式一
import { memo, FC, useRef } from "react";
interface Iprops {
addItem: (value: string) => void;
}
const Home: FC<Iprops> = (props) => {
const inputRef = useRef<HTMLInputElement>(null);
const upone = () => {
let value: string = inputRef.current!.value;
props.addItem(value);
};
return (
<>
<input ref={inputRef} type="text" placeholder="请输入新的todo" />
<button onClick={upone}>add</button>
</>
);
};
export default memo(Home);
绑定的方式二
import { memo, FC, useState } from "react";
interface Iprops {
addItem: (value: string) => void;
}
const Home: FC<Iprops> = (props) => {
const [inputVal, setinputVal] = useState("");
const upone = () => {
props.addItem(inputVal);
};
const handleKeyUp = (event: any) => {
if (event.keyCode === 13) {
props.addItem(inputVal);
}
};
return (
<>
<input
value={inputVal}
onChange={(e) => {
setinputVal(e.target.value);
}}
onKeyUp={handleKeyUp}
type="text"
placeholder="请输入新的todo"
/>
<button onClick={upone}>add</button>
</>
);
};
export default memo(Home);
todoitem.tsx
import { memo, FC } from "react";
import { i_listitem } from "../../interfaces";
import "./item.css";
interface Iprops {
item: i_listitem;
changeStatu: (id: number) => void;
delItem: (id: number) => void;
}
const TodoItem: FC<Iprops> = (props) => {
return (
<div className="td_item">
<input
type="checkbox"
checked={props.item.status}
onChange={() => {
props.changeStatu(props.item.id);
}}
/>
<p>{props.item.content}</p>
<button
onClick={() => {
props.delItem(props.item.id);
}}
>
删除
</button>
</div>
);
};
export default memo(TodoItem);