前言
青训营前端实践文档。 使用React实现一个简单的ToDoList,用户可以添加、编辑和删除。在写之前,我对于react基本上是完全没有了解的。为了满足结营文档要求,我才开始对react有所学习。在学习的过程中,发现这是非常好的一个入门项目,能够让你快速的对于react的基本操作特别是hook有所了解、实践。欢迎关掉文档后重新写一个属于自己的React ToDo List。
How to achieve
环境部署
npx create-react-app todo-list
cd todo-list
npm start
这时,react会自动将你转到localhost: 3000 默认网页。如果网站上有个react图标一直转,则代表你已经完成基础部署。这时候的基本folder里包含很多对于我们网站设立不必要的东西,可以直接删除。具体删除方法 详见我写的另一篇文章: # React 初始界面整理
本文章思考方式与步骤follow react doc instruction react官方文档: Thining in React
Start with the mockup
Imagine that you already have a JSON API and a mockup from a designer. The JSON API returns some data that looks like this:
[
{ id: 1, name: "Buy milk", isDone: false},
{ id: 2, name: "Do Assignment", isDone: false},
{ id: 3, name: "Reading React", isDone: false},
{ id: 4, name: "Writing Daily Blog", isDone: false},
{ id: 5, name: "Kiss my boyfriend 100 times", isDone: true}
]
The mockup looks like this:
To implement a UI in React, we will usually follow the same five steps.
Step 1: Break the UI into a component hierarchy
- ToDoList Table
- Add Bar
- Main List: Lists/ Reminding Label/ Clear Button
Step 2: Build a static version in React
UI 效果
Header Component
export default function Addbar(){
return(
<>
<label>What to do today? </label>
<input type="text" placeholder="Buy Milk" />
</>
);
}
MainList Component
export default function MainList({todos, count_unfinished}){
const count_finished = todos.length - count_unfinished;
return(
<div>
<section>
<ul>
{todos.map(todo=>{
return( <li key={todo.id} style={{color: todo.isDone?"grey":"", textDecoration:todo.isDone?"line-through":""}}>
{todo.name}</li>);
})}
</ul>
</section>
<div>
<p><b>{count_unfinished}</b> {(count_unfinished===1)?"task":"tasks"} left.</p>
<button>Clear {count_finished} completed {(count_finished===1)?"task":"tasks"}</button>
</div>
</div>
);
}
App.js 主文档
import Addbar from "./Components/AddBar"
import MainList from "./Components/MainList";
const TODOS = [
{ id: 1, name: "Buy milk", isDone: false},
{ id: 2, name: "Do Assignment", isDone: false},
{ id: 3, name: "Reading React", isDone: false},
{ id: 4, name: "Writing Daily Blog", isDone: false},
{ id: 5, name: "Kiss my boyfriend 100 times", isDone: true}
]
const count = 1;
export default function WholeList(){
return(
<div>
<Addbar />
<MainList todos={TODOS} count_unfinished={count}/>
</div>
);
}
app js主文档其实应该更为简洁一些,比如可以后续把TODOS移到json文档中等
加上hook useState
这个项目只需要使用useState即可。我之前写的文章: useState in React 有解释useState 基础用法。