Last active
August 12, 2022 23:32
-
-
Save rs6000/93f52a00045a632ca744e6beb325c04f to your computer and use it in GitHub Desktop.
React ToDoList in single file (最陽春版本)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta http-equiv="X-UA-Compatible" content="IE=edge"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<!-- CDN --> | |
<!-- react --> | |
<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script> | |
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script> | |
<!-- babel --> | |
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script> | |
<title>Hello React</title> | |
<!-- css style 不建議這樣寫,簡單範例才使用 --> | |
<style> | |
.done { | |
text-decoration: line-through; | |
} | |
</style> | |
</head> | |
<body> | |
<div id="root"> | |
</div> | |
<!-- 程式區 --> | |
<!-- 要使用JSX 要先啟用 babel 加入 type="text/babel" --> | |
<script type="text/babel"> | |
const { useState } = React; | |
const root = ReactDOM.createRoot(document.getElementById('root')); | |
function TodoList() { | |
const [title, setTitle] = useState('TodoList - React!!!') | |
const [input, setInput] = useState('') | |
const [list, setList] = useState([ | |
{ | |
id: 1, | |
text: '123', | |
status: false | |
}, | |
{ | |
id: 2, | |
text: '456', | |
status: true | |
}, | |
{ | |
id: 3, | |
text: '5566', | |
status: false | |
}, | |
]) | |
const inputHandler = (e) => { | |
setInput(e.target.value) | |
} | |
const addHandler = () => { | |
setInput("") | |
setList(list.concat([ | |
{ | |
id: Date.now(), | |
text: input, | |
status: false | |
} | |
])) | |
} | |
const deleteHandler = (id) => { | |
const newList = list.filter((todo) => { | |
return todo.id !== id | |
}) | |
setList(newList) | |
} | |
const completeHandler = (id) => { | |
const newList = list.map((todo) => { | |
if (todo.id === id) todo.status = !todo.status | |
return todo | |
}) | |
setList(newList) | |
} | |
return ( | |
<div> | |
<h1>{title}</h1> | |
<p><input type="text" value={input} onChange={inputHandler} /><button onClick={addHandler}>Add</button></p> | |
<ul> | |
{ | |
list.map((item) => { | |
return ( | |
<li key={item.id} className={item.status ? "done" : ""}> | |
<input type="checkbox" checked={item.status} onChange={() => completeHandler(item.id)} /> | |
{item.text} | |
<button onClick={() => deleteHandler(item.id)}>Delete</button> | |
</li> | |
) | |
}) | |
} | |
</ul> | |
</div> | |
) | |
} | |
function App() { | |
return ( | |
<TodoList /> | |
) | |
} | |
root.render(<App />) | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment