Home >Web Front-end >JS Tutorial >Detailed steps to implement TodoList with React

Detailed steps to implement TodoList with React

php中世界最好的语言
php中世界最好的语言Original
2017-12-31 10:23:042808browse

What I bring to you this time is the detailed steps of implementing TodoList using React. This article will give you a good analysis.

Let’s first talk about the functions to be implemented

(1) You can add tasks;
(2) The colors of completed tasks and unfinished tasks are distinguished;
(3 ) When adding tasks, modifying task status, and deleting tasks, the following number of completed tasks and total number of tasks will change;

The above are the functions to be implemented.

2. How to design next?

(1) Task storage data structure:

list: [{
      id: 0,
      name: '吃饭',
      status: 0
    }, {
      id: 1,
      name: '睡觉',
      status: 0
    }, {
      id: 2,
      name: '打豆豆',
      status : 0
    }]

Each task has its own id, task name, and task status. The task id is in addition to the identification The uniqueness of the task can also be used as the key value of the list item. We all know that when using lists in react, each item in the list must have a key value. This will allow each list item to be quickly located and reduce unnecessary queries when executing the Diff algorithm, thus helping to improve performance. .

(2) Division of components

TodoList as a whole is treated as a large component;

Each list item (ListItem) in the list is treated as a component;

Add the task box (Dialog) as a component.

3. Specific implementation

Take the implementation of ListItem as an example:

It is necessary to divide the list item into a component separately, so that each separate item They are all independent, making the logic of the code simpler, enhancing the reusability of the code, and making maintenance easier.

Of course, if you are smart, you will definitely think of a problem: every time the status of a Task changes or a Task is added or deleted, the number of tasks completed and the total number will change, but every ListItem How to achieve mutual independence? At this time, communication between parent and child components is used.

If you are a React beginner like me, there will be many articles on Baidu that talk about how to communicate between parent and child components. Let me briefly talk about my simple and crude understanding:

In Define the method of changing state data in the parent and child components, pass the method to the child component in the form of props, trigger the event processing program in the child component, and then execute the function passed by the parent component if certain conditions are met. .

The specific code is as follows:

Code in the parent component:

import React, { Component } from 'react';
import ListItem from './listItem';
import Dialog from './dialog';
import './main.css';
  
class TodoList extends Component {
  constructor (props) {
    super(props);
      
    //初始任务列表
    this.state = {
      list: [{
        id: 0,
        name: '吃饭',
        status: 0
      }, {
        id: 1,
        name: '睡觉',
        status: 0
      }, {
        id: 2,
        name: '打豆豆',
        status : 0
      }],
      finished: 0
    };
  }
    
  //添加新任务,在组件中以props的形式传递给子组件
  addTask (newitem) {
    var allTask = this.state.list;
    allTask.push(newitem);
    this.setState({
      list: allTask
    });
  }
  //更新完成的任务,在组件中以props的形式传递给子组件
  updateFinished (todoItem) {
    var sum = 0;
    this.state.list.forEach( (item) => {
      if (item.id === todoItem.id) {
        item.status = todoItem.status;
      }
      if (item.status === 1) {
        sum++;
      }
    });
    this.setState({
      finished: sum
    });
  }
  
  //更新任务总数,在组件中以props的形式传递给子组件
  updateTotal (todoItem) {
    var obj = [], sum = 0;
    this.state.list.forEach((item) => {
      if (item.id !== todoItem.id) {
        obj.push(item);
        if (item.status === 1 ) {
          sum++;
        }
      }
    });
    this.setState({
      list: obj,
      finished: sum
    });
  }
  
  render () {
    return (
      <div className="container">
        <h1>TodoList</h1>
        <ul>
          { this.state.list.map ((item, index) =>
            <ListItem 
              item={item} 
              finishedChange={this.updateFinished.bind(this)} 
              totalChange={this.updateTotal.bind(this)}
              key={index}
            />
          )}
          <li>{this.state.finished}已完成 / {this.state.list.length}总数</li>
        </ul>
        <Dialog addNewTask={this.addTask.bind(this)} nums={this.state.list.length}/>
      </div>
    );
  }
}
  
export default TodoList;

Code in the child component:

import React, { Component } from &#39;react&#39;;
  
class ListItem extends Component {
  constructor (props) {
    super(props);
  
    this.handleFinished = this.handleFinished.bind(this);
    this.handleDelete = this.handleDelete.bind(this);
  } 
  
  handleFinished () {
    var status = this.props.item.status;
  
    status = (status === 0 ? 1 : 0);
  
    var obj = {
      id: this.props.item.id,
      name: this.props.item.name,
      status: status
    }
      
    this.props.finishedChange(obj); //执行父组件传来的方法
  }
  
  handleDelete () {
    this.props.totalChange(this.props.item); //执行父组件传来的方法
  }
  
  render () {
    const item = this.props.item;
  
    const unfinish = {
      backgroundColor: &#39;#DFFCB5&#39;,
      color: &#39;#2EB872&#39;,
    };
  
    const finish = {
      backgroundColor: &#39;#FFFA9D&#39;,
      color: &#39;#FF9A3C&#39;,
      textDecoration: &#39;line-through&#39;
    }
  
    var itemStyle = item.status === 0 ? unfinish : finish;
      
    return (
      <li key={item.id} style={itemStyle}>
        <span 
          onClick={this.handleFinished} 
          id={item.id}
          className="check-btn"
          style={{backgroundColor: item.status === 0 ? &#39;#fff&#39; : &#39;#A1EAFB&#39;}}
        ></span>
        <span>{ item.name }</span>
        <span onClick={this.handleDelete} className="delete-btn">删除</span>
      </li>
    );
  }
}
  
export default ListItem;

The above is a summary of this small A summary of the exercise. If you are a react newbie like me, I believe you will have a closer understanding of React after writing this.


I believe you have read the above Introduction You have mastered the method. For more exciting information, please pay attention to other related articles on the php Chinese website!

Related reading:

How to use vue to implement login verification

How to use Vue’s custom instructions to complete a drop-down menu

Use jQuery to deduplicate and sort arrays


The above is the detailed content of Detailed steps to implement TodoList with 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