-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathApp.tsx
More file actions
127 lines (118 loc) · 3.07 KB
/
App.tsx
File metadata and controls
127 lines (118 loc) · 3.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
import { useState } from "react";
type Todo = { id: number; title: string };
export default function App() {
const [todos, setTodos] = useState<Todo[]>([]);
const [nextId, setNextId] = useState<number>(1);
const [newTodo, setNewTodo] = useState<string>("");
const [editingTodo, setEditingTodo] = useState<Todo>({ id: -1, title: "" });
const addTodo = () => {
setTodos([...todos, { id: nextId, title: newTodo }]);
setNextId(nextId + 1);
setNewTodo("");
};
const removeTodo = (id: number) => {
setTodos(todos.filter((todo) => todo.id !== id));
};
const moveUp = (index: number) => {
const newTodos = [...todos];
const tmp = newTodos[index];
newTodos[index] = newTodos[index - 1];
newTodos[index - 1] = tmp;
setTodos(newTodos);
};
const moveDown = (index: number) => {
const newTodos = [...todos];
const tmp = newTodos[index];
newTodos[index] = newTodos[index + 1];
newTodos[index + 1] = tmp;
setTodos(newTodos);
};
const editTodo = (todo: Todo) => {
setEditingTodo(todo);
};
const fixTodo = () => {
setTodos(
todos.map((todo) => (todo.id === editingTodo.id ? editingTodo : todo)),
);
setEditingTodo({ id: -1, title: "" });
};
return (
<>
<ul>
{todos.map((todo, i) => (
<li key={todo.id}>
{editingTodo.id === todo.id ? (
<>
<input
value={editingTodo.title}
onChange={(e) => {
setEditingTodo({ id: todo.id, title: e.target.value });
}}
/>
<button
type="button"
onClick={() => {
fixTodo();
}}
>
確定
</button>
</>
) : (
<>
<span>{todo.title}</span>
<button
type="button"
onClick={() => {
editTodo(todo);
}}
>
編集
</button>
</>
)}
<button
type="button"
onClick={() => {
removeTodo(todo.id);
}}
>
削除
</button>
{i > 0 && (
<button
type="button"
onClick={() => {
moveUp(i);
}}
>
↑
</button>
)}
{i < todos.length - 1 && (
<button
type="button"
onClick={() => {
moveDown(i);
}}
>
↓
</button>
)}
</li>
))}
</ul>
<div>
<input
value={newTodo}
onChange={(e) => {
setNewTodo(e.target.value);
}}
/>
<button type="button" onClick={addTodo}>
追加
</button>
</div>
</>
);
}