Home >Web Front-end >Front-end Q&A >How to implement todolist using react

How to implement todolist using react

藏色散人
藏色散人Original
2022-12-29 11:26:052734browse

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>待办事项</h2>

                <hr>
                
                <ul>
                    {/* 多个li,后面会循环输出 */}
                    <li>
                        <input> -- <button>删除</button>
                    </li>
                </ul>           



                <h2>已完成事项</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