How to implement todolist using react
How to use react to implement todolist: 1. Create a new project folder Code; 2. Create a react project through the "create-react-app todo-list" command; 3. Create a new ToDoList under the components folder. jsx file; 4. Use an array to save data, and each element in the array is an object; 5. Write the page layout; 6. Add keyboard events, monitor input changes, and implement to-do items and completed items.
The operating environment of this tutorial: Windows 10 system, react18.0.0 version, Dell G3 computer.
How to implement todolist using react?
React Getting Started Practical Example - ToDoList Implementation
Summary:
I have been studying React for a short period of time recently and have a little understanding of the basics of some React development components. Following the teaching video, I implemented the function of a ToDoList component. Today I will record the process of making this component to deepen my learning impression. As a reference for the same front-end beginners.
1. Example display and function introduction
1.1 Example display
Video 1.1
1.2 Function introduction
- Add a to-do item, press the enter key to confirm, and clear the input box at the same time;
- You can switch between to-do and done items by checking whether the checkbox is checked ;
- Click Delete to delete items
2. Preparation work
2.1 Environment configuration reminder
Before preparation: This article assumes development The environment has been configured, including:
- Node.js has been installed;
- cnpm has been installed; npm install -g cnpm --registry=https://registry. npm.taobao.org
- The scaffolding tool has been installed; npm install -g create-react-app / cnpm install -g create-react-app
Note: First time An error that prohibits running scripts will occur when configuring the scaffolding. For the solution, click: https://www.php.cn/link/e543789a8d5b6a0e6b2f2a804d207e8d
2.2 Create a new React project
1. Create a new project folder Code, use VSCode, and add the Code file to the workspace;
Figure 2.1
2. Right-click the Code folder and select Open in Terminal in the tab;
Figure 2.2
3. Enter the following command in the terminal to create a new React project: create-react-app todo-list
Figure 2.3
4. Generate the Rreact project as follows:
Figure 2.4
React development is mainly for src The files in are manipulated. node_modules mainly prevents various dependent packages, public places some public files, and package.json is some configuration files, which will not be described in detail here.
2.3 File classification
- Create a new components folder in the src directory to place the components you create;
- Create a new assets file in the src directory to add it To prevent static resources such as css files and image files;
As shown in Figure 2.5:
Figure 2.5
3. Implementation process
3.1 Create component ToDoList
Create a new ToDoList.jsx file in the components folder and write it as follows Code, set up the basic framework of a component; the code is as follows:
//导入React相关依赖 import React from 'react'; //创建一个组件 class ToDoList extends React.Component{ //构造函数 constructor(props){ super(props); //this是父组件(类)的一个实例,实例就类似于java里的一个类,创建了这个类型的一个对象,这个对象就是实例 this.state = { //this.state里可以写一些初始化的数据 } } //render渲染虚拟DOM render(){ return( <div> ToDoList </div> ); } } //输出组件,使得该组件可以被其他组件调用 export default ToDoList;
- import导入的依赖;
- 组件(class XXX extends React,Component);
- 构造函数constructor;
- render函数;
- export输出组件;
3.2 功能实现与解析
1.初始化数据
使用一个数组来保存数据,数组中每个元素为一个对象,该对象包括两个字段:title和checked,tile为字符串类型,checked为布尔类型,用来区分待办(false)和已办(true);
list:[ { title:'吃饭', checked:true }, { title:'跑步', checked:false }, { title:'上班', checked:false }, { title:'睡觉', checked:true }, ]
该数组在this.state中初始化:
constructor(props){ super(props); //this是父组件(类)的一个实例,实例就类似于java里的一个类,创建了这个类型的一个对象,这个对象就是实例 this.state = { //this.state里可以写一些初始化的数据 list:[ { title:'吃饭', checked:true }, { title:'跑步', checked:false }, { title:'上班', checked:false }, { title:'睡觉', checked:true }, ], } }
2.编写页面布局
页面分为顶部的输入框(input)和下面的 待办事项列表 和已办事项列表;在render中的return中编写(jsx);
render(){ return( <div> <header>TodoList: <input> </header> <h2 id="待办事项">待办事项</h2> <hr> <ul> {/* 多个li,后面会循环输出 */} <li> <input> -- <button>删除</button> </li> </ul> <h2 id="已完成事项">已完成事项</h2> <hr> <ul> {/* 多个li,后面会循环输出 */} <li> <input> -- <button>删除</button> </li> </ul> </div> ); }
3.挂载到根节点下
在index.js下,引入ToDoList组件
import ToDoList from './components/ToDoList';
然后挂在组件ToDoList
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import * as serviceWorker from './serviceWorker'; import ToDoList from './components/ToDoList'; ReactDOM.render( <react.strictmode> {/* 此处是ToDoList组件 */} <todolist></todolist> </react.strictmode>, document.getElementById('root') ); // If you want your app to work offline and load faster, you can change // unregister() to register() below. Note this comes with some pitfalls. // Learn more about service workers: https://bit.ly/CRA-PWA serviceWorker.unregister();
简陋渲染效果如下:
图3.1
3.功能实现
添加待办事项
(1)使用ref属性,获取input输入值:
在input标签上设置属性ref="inputToDo",然后在方法中可以通过 this.refs.inputToDo.value获取输入值;
(2)添加键盘事件,监听输入变化,当输入enter时,添加待办事项;
使用onKeyUp(键盘弹起)/onKeyDown(键盘按下)事件来监听键盘变化。当键盘变化后,触发添加函数,将输入值添加到待办事项中;代码如下:
jsx:
<header>TodoList: <input> </header>
addToDo函数:
addToDo = (event) => { console.log(event.keyCode); if(event.keyCode === 13) { let tempList = this.state.list; tempList.push({ title:this.refs.inputToDo.value, checked:false, }); this.setState({ list:tempList, }); this.refs.inputToDo.value = ''; } }
(3)在constructor中使用bind绑定addToDo,这一步是必须的,否则方法不能执行,所有的方法都需要像这样绑定;
this.addToDo = this.addToDo.bind(this);
图3.2
效果:
视频3.1
输出待办事项和已办事项
使用map方法,循环遍历数组,输出每组数据;代码如下:
-
{/* 多个li,后面会循环输出 */}
{
this.state.list.map((value,index)=>{
{/*checked为false表示待办*/}
if(!value.checked)
{
return (
- {/* */} <input> {value.title}-- <button>删除</button> ); } }) }
checked = {value.checked}表示复选框是否打勾,onChange事件触发一个改变事项状态的方法,index是数组的索引,该方法在下文实现;
效果:
图3.3
待办和已办互相转换
这一步的思路也很简单,其实就是在触发checkbox的onChange事件时,将某一个事项的checked值变为相反的值(true->false/false->true),所以onChange后的方法需要传入数组的索引值,具体实现代码如下:
jsx
<input> {value.title}-- <button>删除</button>
checkboxChange
checkboxChange = (index) => { let tempList = this.state.list; tempList[index].checked = !tempList[index].checked; this.setState({ list:tempList, }); }
效果:
视频3.2
删除事项
删除事项比较简单了,思路也是类似的,在button上添加onClick按钮,触发删除事件,传入参数index,然后根据index,使用数组的splice函数,删除某一待办事项。
arrayA.splice(index,n)
该方法第一个参数是数组中的元素位置,第二个参数是从index开始删除多少个元素。
具体实现如下:
jsx
removeToDo
removeToDo = (index) => { let tempList = this.state.list; tempList.splice(index,1); this.setState({ list:tempList, }); }
效果:即为开篇展示的效果
3.3 编写样式
样式随便写了一下,不太好看,这里也把代码丢上来吧;
index.css
.list{ padding: 10px; } .list li{ line-height: 40px; margin-left: 30px; } .title{ height: 44px; line-height: 44px; text-align: center; background: #000; color:#fff; } .title input{ height: 40px; } .container{ width: 800px; height: 1000px; margin-left: auto; margin-right: auto; background-color: #D0D0D0; border: #fff solid 1px; border-radius: 5px; } .container h2{ margin-left: 20px; } .del-btn { float: right; margin-right: 30px; }
引入样式
在ToDoList.jsx中按如下代码引入index.css
import '../assets/index.css';
3.4 整体效果
视频3.3:整体效果展示
四、整体代码
- ToDoList.jsx


//导入React相关依赖 import React from 'react'; import '../assets/index.css'; //创建一个组件 class ToDoList extends React.Component{ //构造函数 constructor(props){ super(props); //this是父组件(类)的一个实例,实例就类似于java里的一个类,创建了这个类型的一个对象,这个对象就是实例 this.state = { //this.state里可以写一些初始化的数据 list:[ { title:'吃饭', checked:true }, { title:'跑步', checked:false }, { title:'上班', checked:false }, { title:'睡觉', checked:true }, ], } this.addToDo = this.addToDo.bind(this); this.checkboxChange = this.checkboxChange.bind(this); } addToDo = (event) => { console.log(event.keyCode); if(event.keyCode === 13) { let tempList = this.state.list; tempList.push({ title:this.refs.inputToDo.value, checked:false, }); this.setState({ list:tempList, }); this.refs.inputToDo.value = ''; } } checkboxChange = (index) => { let tempList = this.state.list; tempList[index].checked = !tempList[index].checked; this.setState({ list:tempList, }); } removeToDo = (index) => { let tempList = this.state.list; tempList.splice(index,1); this.setState({ list:tempList, }); } //render渲染虚拟DOM render(){ return(<header>TodoList: <input> </header>); } } //输出组件,使得该组件可以被其他组件调用 export default ToDoList;待办事项
{/* 多个li,后面会循环输出 */} { this.state.list.map((value,index)=>{ if(!value.checked) { return (
- {value.title}
); } }) }已完成事项
{/* 多个li,后面会循环输出 */} { this.state.list.map((value,index)=>{ if(value.checked) { return (
- {value.title}
); } }) }
index.css
.red{ color:red; } .list{ padding: 10px; } .list li{ line-height: 40px; margin-left: 30px; } .title{ height: 44px; line-height: 44px; text-align: center; background: #000; color:#fff; } .title input{ height: 40px; } .container{ width: 800px; height: 1000px; margin-left: auto; margin-right: auto; background-color: #D0D0D0; border: #fff solid 1px; border-radius: 5px; } .container h2{ margin-left: 20px; } .del-btn { float: right; margin-right: 30px; }
index.js
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import * as serviceWorker from './serviceWorker'; import ToDoList from './components/ToDoList'; ReactDOM.render( <react.strictmode> {/* <app></app> */} <todolist></todolist> </react.strictmode>, document.getElementById('root') ); // If you want your app to work offline and load faster, you can change // unregister() to register() below. Note this comes with some pitfalls. // Learn more about service workers: https://bit.ly/CRA-PWA serviceWorker.unregister();
五、结语
结语就算了吧,好困,睡了。
写博客费时间啊,大家要是看到有啥不对的地方,麻烦联系我修改哈,我水平太有限了,谢谢大佬们了。
推荐学习:《react视频教程》
The above is the detailed content of How to implement todolist using react. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How to build a real-time chat application using React and WebSocket Introduction: With the rapid development of the Internet, real-time communication has attracted more and more attention. Live chat apps have become an integral part of modern social and work life. This article will introduce how to build a simple real-time chat application using React and WebSocket, and provide specific code examples. 1. Technical preparation Before starting to build a real-time chat application, we need to prepare the following technologies and tools: React: one for building

React front-end and back-end separation guide: How to achieve front-end and back-end decoupling and independent deployment, specific code examples are required In today's web development environment, front-end and back-end separation has become a trend. By separating front-end and back-end code, development work can be made more flexible, efficient, and facilitate team collaboration. This article will introduce how to use React to achieve front-end and back-end separation, thereby achieving the goals of decoupling and independent deployment. First, we need to understand what front-end and back-end separation is. In the traditional web development model, the front-end and back-end are coupled

How to use React and Flask to build simple and easy-to-use web applications Introduction: With the development of the Internet, the needs of web applications are becoming more and more diverse and complex. In order to meet user requirements for ease of use and performance, it is becoming increasingly important to use modern technology stacks to build network applications. React and Flask are two very popular frameworks for front-end and back-end development, and they work well together to build simple and easy-to-use web applications. This article will detail how to leverage React and Flask

How to build a reliable messaging application with React and RabbitMQ Introduction: Modern applications need to support reliable messaging to achieve features such as real-time updates and data synchronization. React is a popular JavaScript library for building user interfaces, while RabbitMQ is a reliable messaging middleware. This article will introduce how to combine React and RabbitMQ to build a reliable messaging application, and provide specific code examples. RabbitMQ overview:

How to use React and Google BigQuery to build fast data analysis applications Introduction: In today's era of information explosion, data analysis has become an indispensable link in various industries. Among them, building fast and efficient data analysis applications has become the goal pursued by many companies and individuals. This article will introduce how to use React and Google BigQuery to build a fast data analysis application, and provide detailed code examples. 1. Overview React is a tool for building

React code debugging guide: How to quickly locate and resolve front-end bugs Introduction: When developing React applications, you often encounter a variety of bugs that may crash the application or cause incorrect behavior. Therefore, mastering debugging skills is an essential ability for every React developer. This article will introduce some practical techniques for locating and solving front-end bugs, and provide specific code examples to help readers quickly locate and solve bugs in React applications. 1. Selection of debugging tools: In Re

ReactRouter User Guide: How to Implement Front-End Routing Control With the popularity of single-page applications, front-end routing has become an important part that cannot be ignored. As the most popular routing library in the React ecosystem, ReactRouter provides rich functions and easy-to-use APIs, making the implementation of front-end routing very simple and flexible. This article will introduce how to use ReactRouter and provide some specific code examples. To install ReactRouter first, we need

React Responsive Design Guide: How to Achieve Adaptive Front-end Layout Effects With the popularity of mobile devices and the increasing user demand for multi-screen experiences, responsive design has become one of the important considerations in modern front-end development. React, as one of the most popular front-end frameworks at present, provides a wealth of tools and components to help developers achieve adaptive layout effects. This article will share some guidelines and tips on implementing responsive design using React, and provide specific code examples for reference. Fle using React
