基于React实现TodoList简单案例

需求

image

1) 添加任务
2) 删除任务
3) 更新任务状态
4) 全选/全不选
5) 清除已完成的任务

组件的划分

image

  • TodoList整体作为一个大组件;

  • Header:input添加

  • List:列表作为一个组件;

  • Item: 列表中的每个列表项(ListItem)作为一个组件

  • Footer:底部展示和功能作为一个组件

代码编写

App.js 父组件


import React, { Component } from 'react'

import Header from './components/Header'
import Footer from './components/Footer'
import List from './components/List'

import './App.css';

export default class App extends Component {
  state = {
    todoList: [
      { id: 1, name: "吃饭", done: true },
      { id: 2, name: "睡觉", done: true },
      { id: 3, name: "逛街", done: false },
      { id: 4, name: "上班", done: false }
    ]
  }
  // 添加todo
  addTodo = (todoObj) => { 
    const {todoList} = this.state;
    const newTodoList = [todoObj,...todoList]
    this.setState({
      todoList:newTodoList
    })
  }
  // 更新todo
  updataTodo = (id,done) => {
    const { todoList } = this.state;
    const newTodos = todoList.map((item) => {
      if (item.id === id) {
        return { ...item, done: done }
      } else {
        return item
      }
    })
    this.setState({ todoList: newTodos })
  }

  // 删除
  delTodo = (id) => { 
    const { todoList } = this.state;
    const newTodos = todoList.filter( (item) => {
      return item.id !== id
    })
    this.setState({ todoList: newTodos })
  }

  // 全选/全不选
  allChecked = (done) => {
    const { todoList } = this.state;
    const newTodos = todoList.map((item) => { 
      return { ...item, done: done } 
    })
    this.setState({ todoList : newTodos })
  }
  // 清除所以已经完成的任务
  clearAllDone = () => {
    const { todoList } = this.state;
    const newTodos = todoList.filter((item) => { 
      return !item.done  
    })
    this.setState({ todoList : newTodos })
  }

  render() {
    const { todoList } = this.state
    return (
      <div className="todo-container">
        <div className="todo-wrap">
          <h2>todoList案例</h2>
          <Header addTodo={this.addTodo}/>
          <List todoList={todoList} updataTodo={this.updataTodo} delTodo={this.delTodo}/>
          <Footer todoList={todoList} allChecked={this.allChecked} clearAllDone={this.clearAllDone}/>
        </div>
      </div>
    )
  }
}


body {
  background: #fff;
}

.btn {
  display: inline-block;
  padding: 4px 12px;
  margin-bottom: 0;
  font-size: 14px;
  line-height: 20px;
  text-align: center;
  vertical-align: middle;
  cursor: pointer;
  box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05);
  border-radius: 4px;
}

.btn-danger {
  color: #fff;
  background-color: #da4f49;
  border: 1px solid #bd362f;
}

.btn-danger:hover {
  color: #fff;
  background-color: #bd362f;
}

.btn:focus {
  outline: none;
}

.todo-container {
  width: 600px;
  margin: 0 auto;
}
.todo-container .todo-wrap {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
}

Header 组件


import React, { Component } from 'react'
import { nanoid } from 'nanoid' 
import './index.css'

export default class index extends Component {
    // 处理input enter事件
    handleKeyUp = (event) => {
        if(event.keyCode !== 13) return
        if(event.target.value.trim() === ''){
            alert("请输入值")
            return
        }  
        const todoObj = {
            id:nanoid(),
            name:event.target.value,
            done:false
        }
        this.props.addTodo(todoObj);
        event.target.value = "";
    }
    render() {
        return (
            <div className="todo-header">
                <input type="text" placeholder="请输入你的任务名称,按回车键确认" onKeyUp={this.handleKeyUp}/>
            </div>
        )
    }
}
.todo-header input {
  width: 560px;
  height: 28px;
  font-size: 14px;
  border: 1px solid #ccc;
  border-radius: 4px;
  padding: 4px 7px;
}

.todo-header input:focus {
  outline: none;
  border-color: rgba(82, 168, 236, 0.8);
  box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(82, 168, 236, 0.6);
}

List 组件


.todo-main {
    margin-left: 0px;
    border: 1px solid #ddd;
    border-radius: 2px;
    padding: 0px;
}

.todo-empty {
    height: 40px;
    line-height: 40px;
    border: 1px solid #ddd;
    border-radius: 2px;
    padding-left: 5px;
    margin-top: 10px;
}




import React, { Component } from 'react'

import Item from '../Item'
import './index.css'

export default class index extends Component {
    render() {
        const { todoList,updataTodo,delTodo } = this.props
        return (
            <ul className="todo-main">
                {
                    todoList.map( (todo) => {
                        return <Item {...todo} key={todo.id} updataTodo={updataTodo} delTodo={delTodo}/>
                    })
                } 
            </ul>
        )
    }
}

Item 组件


import React, { Component } from 'react'

import './index.css'

export default class index extends Component {
    // 处理鼠标的移入移出事件 
    state = {
        mouse:false
    }

    handleMouse = (mouse) => { 
        return ()=>{
            this.setState({
                mouse:mouse
            })
        }
    }
    // 更新todo状态
    handleChecked = (id) => {
        return (event) => { 
            this.props.updataTodo(id,event.target.checked);
        }
    }
    handleDel = (id) => {
        return () => {
            this.props.delTodo(id);
        }
    }

    render() {
        const {name,id,done} = this.props
        const {mouse} = this.state
        return (
            <li onMouseLeave={this.handleMouse(false)} onMouseEnter={this.handleMouse(true)} style={{ background : mouse ? '#ddd' : 'white'}}>
                <label>
                    <input type="checkbox" checked={done} onChange={this.handleChecked(id)}/>
                    <span>{name}</span>
                </label>
                <button className="btn btn-danger" style={{display: mouse ? 'block' : 'none'}} onClick={this.handleDel(id)}>删除</button>
            </li>
        )
    }
}


li {
    list-style: none;
    height: 36px;
    line-height: 36px;
    padding: 0 5px;
    border-bottom: 1px solid #ddd;
    
}

li label {
    float: left;
    cursor: pointer;
}

li label li input {
    vertical-align: middle;
    margin-right: 6px;
    position: relative;
    top: -1px;
}

li button {
    float: right;
    display: none;
    margin-top: 3px;
}

li:before {
    content: initial;
}

li:last-child {
    border-bottom: none;
}


import React, { Component } from 'react'

import './index.css'

export default class index extends Component {

    // 全选/全不选 
    handleChange = (event) => { 
        this.props.allChecked(event.target.checked)
    }
    handleClick = () => {
        this.props.clearAllDone()
    }

    render() {
        const {todoList} = this.props;
        const doneCount = todoList.reduce((pre,todo)=> pre + (todo.done ? 1 : 0),0);
        const allCount = todoList.length;
        return (
            <div className="todo-footer">
                <label>
                    <input type="checkbox" onChange={this.handleChange} checked={ doneCount === allCount && allCount !== 0 ? true : false }/>
                </label>
                <span>
                    <span>已完成 {doneCount}</span> / 全部 {allCount}
                </span>
                <button className="btn btn-danger" onClick={this.handleClick}>清除已完成任务</button>
            </div>
        )
    }
}


.todo-footer {
    height: 40px;
    line-height: 40px;
    padding-left: 6px;
    margin-top: 5px;
}

.todo-footer label {
    display: inline-block;
    margin-right: 20px;
    cursor: pointer;
}

.todo-footer label input {
    position: relative;
    top: -1px;
    vertical-align: middle;
    margin-right: 5px;
}

.todo-footer button {
    float: right;
    margin-top: 5px;
}

案例总结

动态初始化列表,如何确定将数据放在哪个组件的state中?

  • 某个组件使用:放在其自身的state中

  • 某些组件使用:放在他们共同的父组件state中(状态提升)

父子组件间如何通信

在父子组件中定义改变state数据的方法,将方法以props的形式传递给子组件,在子组件中触发事件处理程序,然后满足某种条件的话就执行父组件传来的函数。

  • 【父组件】给【子组件】传递数据:通过props传递

  • 【子组件】给【父组件】传递数据:通过props传递,要求父提前给子传递一个函数

注意defaultChecked 和 checked的区别,类似的还有:defaultValue 和 value

defaultChecked 默认属性 只在初始化数据的时候赋值

状态在哪里,操作状态的方法就在哪里

posted @ 2021-03-17 11:45  流年瓦解我们的记忆  阅读(829)  评论(0编辑  收藏  举报