search
HomeWeb Front-endFront-end Q&AHow to implement todolist using react

How to implement todolist using react

Dec 29, 2022 am 11:26 AM
reacttodolist

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.

How to implement todolist using react

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

How to implement todolist using react

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;
The function of each part of the component is briefly described in the comments. A basic component generally includes the above parts:
  • 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

效果:

 How to implement todolist using react

视频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

  • 待办和已办互相转换

  这一步的思路也很简单,其实就是在触发checkboxonChange事件时,将某一个事项的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,
     });
}

 效果:

How to implement todolist using react

 视频3.2

  • 删除事项

 删除事项比较简单了,思路也是类似的,在button上添加onClick按钮,触发删除事件,传入参数index,然后根据index,使用数组的splice函数,删除某一待办事项。

arrayA.splice(index,n)

该方法第一个参数是数组中的元素位置,第二个参数是从index开始删除多少个元素。

具体实现如下:

jsx

  
  •         {value.title}        --   
  •  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 整体效果

     How to implement todolist using react

    视频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>                     
                            

    待办事项

                            
                            
                                  {/* 多个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}                                                                                              
    •                                         );                                     }                                 })                             }                         
                          
                                
            );     } } //输出组件,使得该组件可以被其他组件调用 export default ToDoList;
    View Code
    • 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!

    Statement
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    The Benefits of React: Performance, Reusability, and MoreThe Benefits of React: Performance, Reusability, and MoreApr 15, 2025 am 12:05 AM

    React’s popularity includes its performance optimization, component reuse and a rich ecosystem. 1. Performance optimization achieves efficient updates through virtual DOM and diffing mechanisms. 2. Component Reuse Reduces duplicate code by reusable components. 3. Rich ecosystem and one-way data flow enhance the development experience.

    React: Creating Dynamic and Interactive User InterfacesReact: Creating Dynamic and Interactive User InterfacesApr 14, 2025 am 12:08 AM

    React is the tool of choice for building dynamic and interactive user interfaces. 1) Componentization and JSX make UI splitting and reusing simple. 2) State management is implemented through the useState hook to trigger UI updates. 3) The event processing mechanism responds to user interaction and improves user experience.

    React vs. Backend Frameworks: A ComparisonReact vs. Backend Frameworks: A ComparisonApr 13, 2025 am 12:06 AM

    React is a front-end framework for building user interfaces; a back-end framework is used to build server-side applications. React provides componentized and efficient UI updates, and the backend framework provides a complete backend service solution. When choosing a technology stack, project requirements, team skills, and scalability should be considered.

    HTML and React: The Relationship Between Markup and ComponentsHTML and React: The Relationship Between Markup and ComponentsApr 12, 2025 am 12:03 AM

    The relationship between HTML and React is the core of front-end development, and they jointly build the user interface of modern web applications. 1) HTML defines the content structure and semantics, and React builds a dynamic interface through componentization. 2) React components use JSX syntax to embed HTML to achieve intelligent rendering. 3) Component life cycle manages HTML rendering and updates dynamically according to state and attributes. 4) Use components to optimize HTML structure and improve maintainability. 5) Performance optimization includes avoiding unnecessary rendering, using key attributes, and keeping the component single responsibility.

    React and the Frontend: Building Interactive ExperiencesReact and the Frontend: Building Interactive ExperiencesApr 11, 2025 am 12:02 AM

    React is the preferred tool for building interactive front-end experiences. 1) React simplifies UI development through componentization and virtual DOM. 2) Components are divided into function components and class components. Function components are simpler and class components provide more life cycle methods. 3) The working principle of React relies on virtual DOM and reconciliation algorithm to improve performance. 4) State management uses useState or this.state, and life cycle methods such as componentDidMount are used for specific logic. 5) Basic usage includes creating components and managing state, and advanced usage involves custom hooks and performance optimization. 6) Common errors include improper status updates and performance issues, debugging skills include using ReactDevTools and Excellent

    React and the Frontend Stack: The Tools and TechnologiesReact and the Frontend Stack: The Tools and TechnologiesApr 10, 2025 am 09:34 AM

    React is a JavaScript library for building user interfaces, with its core components and state management. 1) Simplify UI development through componentization and state management. 2) The working principle includes reconciliation and rendering, and optimization can be implemented through React.memo and useMemo. 3) The basic usage is to create and render components, and the advanced usage includes using Hooks and ContextAPI. 4) Common errors such as improper status update, you can use ReactDevTools to debug. 5) Performance optimization includes using React.memo, virtualization lists and CodeSplitting, and keeping code readable and maintainable is best practice.

    React's Role in HTML: Enhancing User ExperienceReact's Role in HTML: Enhancing User ExperienceApr 09, 2025 am 12:11 AM

    React combines JSX and HTML to improve user experience. 1) JSX embeds HTML to make development more intuitive. 2) The virtual DOM mechanism optimizes performance and reduces DOM operations. 3) Component-based management UI to improve maintainability. 4) State management and event processing enhance interactivity.

    React Components: Creating Reusable Elements in HTMLReact Components: Creating Reusable Elements in HTMLApr 08, 2025 pm 05:53 PM

    React components can be defined by functions or classes, encapsulating UI logic and accepting input data through props. 1) Define components: Use functions or classes to return React elements. 2) Rendering component: React calls render method or executes function component. 3) Multiplexing components: pass data through props to build a complex UI. The lifecycle approach of components allows logic to be executed at different stages, improving development efficiency and code maintainability.

    See all articles

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    AI Hentai Generator

    AI Hentai Generator

    Generate AI Hentai for free.

    Hot Article

    R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
    4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. Best Graphic Settings
    4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. How to Fix Audio if You Can't Hear Anyone
    4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    WWE 2K25: How To Unlock Everything In MyRise
    1 months agoBy尊渡假赌尊渡假赌尊渡假赌

    Hot Tools

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    DVWA

    DVWA

    Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

    EditPlus Chinese cracked version

    EditPlus Chinese cracked version

    Small size, syntax highlighting, does not support code prompt function

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    Safe Exam Browser

    Safe Exam Browser

    Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.