使用React实现待办事项列表
在这个笔记中,我们将学习如何使用React创建一个简单的待办事项列表应用程序,用户可以添加、编辑和删除待办事项。
准备工作
确保你已经安装了Node.js和npm(Node.js包管理器)。
创建新的React应用
首先,我们需要创建一个新的React应用。打开命令行界面并运行以下命令:
npx create-react-app todo-app
cd todo-app
npm start
这将创建一个名为todo-app 的新React应用,并启动开发服务器。
编写组件
我们将开始编写待办事项列表组件。
- 打开
src/App.js文件并清除其中的所有代码。 - 然后,将以下代码粘贴到
App.js文件中:
import React, { useState } from 'react';
import './App.css';
function App() {
const [todos, setTodos] = useState([]);
const [inputValue, setInputValue] = useState('');
const addTodo = () => {
if (inputValue.trim() === '') return;
setTodos([...todos, inputValue]);
setInputValue('');
};
const deleteTodo = (index) => {
const updatedTodos = todos.filter((_, i) => i !== index);
setTodos(updatedTodos);
};
return (
<div className="App">
<h1>Todo List</h1>
<input
type="text"
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
placeholder="Add a new todo"
/>
<button onClick={addTodo}>Add</button>
<ul>
{todos.map((todo, index) => (
<li key={index}>
{todo}
<button onClick={() => deleteTodo(index)}>Delete</button>
</li>
))}
</ul>
</div>
);
}
export default App;
样式
为了美化应用程序,我们可以在 src/App.css 中添加一些基本样式:
.App {
text-align: center;
margin-top: 50px;
}
input {
padding: 8px;
margin-right: 10px;
}
button {
padding: 8px 12px;
background-color: #007bff;
color: white;
border: none;
cursor: pointer;
}
ul {
list-style: none;
padding: 0;
}
li {
display: flex;
align-items: center;
justify-content: space-between;
margin: 10px 0;
}
button {
background-color: #dc3545;
}
运行应用程序
保存文件后,回到命令行界面,确保仍然在 todo-app 目录中,然后运行 npm start 命令。这将在浏览器中打开一个新的标签页,显示你的待办事项列表应用程序。
现在,你可以在输入框中添加待办事项,点击"Add" 按钮添加,每个事项都会显示在列表中。每个事项旁边都有一个"Delete" 按钮,点击该按钮可以删除对应的待办事项。