以todolist为例

在这里插入图片描述

在这里插入图片描述

目录如下

在这里插入图片描述

app.js

 import React, {  PureComponent } from 'react'
import Input from './components/Input'
import List from './components/List'
import Total from './components/Total'
import Mask from './components/Mask'
import { bus as $bus } from './components/bus'
import './App.css'
export default class App extends PureComponent {
  constructor() {
    super()
    this.state = {
      flag: false,
      list: [
        {
          id: 1,
          content: '哈哈哈',
          checked: false
        },
        {
          id: 7,
          content: '哈哈哈',
          checked: false
        },
        {
          id: 5,
          content: '哈哈哈',
          checked: false
        },
      ],
      checkAll: false,
      selectLength: 0,
      item: {}
    }
  }
  // 全选全不选
  checkAllHandler(checked) {
    console.log("checked",checked);
    const { list } = this.state
    const newList = list.map(item =>{
      return {...item,checked}
    })
    this.setState({list:newList,checkAll: checked},()=>{
      this.doneLenth()
    })
  }
  // 单选单不选
  checkHandler =(id,checked)=> {
    const { list } = this.state
    const newList = list.map(item => {
      return item.id === id ? {...item,checked} : item
    })
    let checkAll = newList.length && newList.every(item => item.checked)
    this.setState(() => ({list: newList,checkAll}),()=>{
      this.doneLenth()
    })
  }
  // 添加 
  addHandler = (obj)=>{
    let { list } = this.state;
    let newList = [...list,obj]
    console.log('newList====' newList)
    this.setState({
      list: newList,
    },()=>{
      this.doneLenth()
    })
  } 
  // 搜索
  searchHandler=(content)=>{
    console.log("content",content);
    let { list } = this.state;
    let newList = list.filter(item => item.content.includes(content))
    this.setState({
      list: newList
    },()=>{
      this.doneLenth()
    })
  }
  // 删除
  delHandler = (id)=> {
    console.log("id",id);
    const { list } = this.state
    const newList = list.filter(item => item.id !=id)
    let checkAll = newList.length && newList.every(item => item.checked)
    this.setState(() => ({list: newList,checkAll}),()=>{
      this.doneLenth()
    })
  }
  // 编辑
  editHandler = (items)=>{
    this.setState({
      item: items
    })
  }
  // 更新
  update = (content)=>{
    const { list,item } = this.state
    let obj = Object.assign(item,{content})
    const newList = list.map(v =>{
      if(v.id === obj.id) {
        v = {...obj}
      }
      return v
    })
    this.setState({
      list: newList,
      item: obj
    })
  }
  // 已完成 
  doneLenth=()=> {
    const { list } = this.state
    const newList = list.filter(item => item.checked)
    let selectLength = newList.length
    setTimeout(()=>{
      this.setState({
        selectLength
      })
    })
  }
  // 挂载
  componentDidMount() {
    this.unSubscribe = $bus.addListener("getFlag",(flag)=>{
      this.setState({flag})
    })
    this.unSubscribe1 = $bus.addListener("sendValue",(obj)=>{
     this.addHandler(obj)
    })
    this.unSubscribe2 = $bus.addListener("searchValue",(value)=>{
     this.searchHandler(value)
    })
    this.unSubscribe3 = $bus.addListener("getItem",(item)=>{
     this.editHandler(item)
    })
    this.unSubscribe4 = $bus.addListener("update",(content)=>{
     this.update(content)
    })
  }
  // 卸载
  componentWillUnmount() {
    $bus.removeListener(this.unSubscribe)
    $bus.removeListener(this.unSubscribe1)
    $bus.removeListener(this.unSubscribe2)
    $bus.removeListener(this.unSubscribe3)
    $bus.removeListener(this.unSubscribe4)
  }
  render() {
    let { flag, list,checkAll,selectLength } = this.state
    return (
      <div className='container'>
        {/* 输入框 */}
        <Input></Input>
        {/* 列表 */}
        <List list={list} checkHandler={this.checkHandler} delHandler={this.delHandler}></List>
        {/* 统计 */}
        <Total checkAllHandler={this.checkAllHandler.bind(this)} checkAll={checkAll} selectLength={selectLength}></Total>
        {/* 编辑弹框 */}
        { flag ? <Mask ></Mask> : ''}
      </div>
    )
  }
}

Input.js

import React, { Component } from 'react'
import { bus as $bus } from './bus'
export default class Input extends Component {
  constructor() {
    super()
    this.state = {
      value:""
    }
  }
  changeHandler = (e)=>{
    this.setState({
      value: e.target.value
    })
    console.log("this.state.value",this.state.value);
  }
  // 添加
  addHandler = ()=>{
    let { value } = this.state;
    let obj = {
      id: Date.now(),
      content: value,
      done: false
    }
    if(value) {
      $bus.emit("sendValue",obj)
    } else {
      console.log("请输入")
    }
  }
  // 搜索
  searchHandler = ()=>{
    console.log("搜索");
    let { value } = this.state;
    if(!value) return console.log("请输入");
    $bus.emit("searchValue",value)
  }
  render() {
    let { value } = this.state
    return (
      <>
        <div className="input">
          <input type="text" value={value} placeholder='请输入你的任务名称,按回车键确认' onInput={this.changeHandler}/>
          <button className="btn btn-success" onClick={this.addHandler}>添加</button>
          <button className="btn btn-primary" onClick={this.searchHandler}>搜索</button>
        </div>
      </>
    )
  }
}

List.js

import React, { Component } from 'react'
import Item from './Item'
import PropTypes from 'prop-types'
export default class List extends Component {
  static propTypes = {
		list:PropTypes.array.isRequired,
	}
  render() {
    let { list,checkHandler,checkAllHandler,delHandler } = this.props;
    console.log("list",list);
    return (
      <ul className="task-list">
        {
          list.map(item => (<Item item={item} key={item.id} checkHandler={checkHandler} checkAllHandler={checkAllHandler} delHandler={delHandler}></Item>))
        }
      </ul>
    )
  }
}

Item.js

import React, { Component } from 'react'
import { bus as $bus } from './bus'
export default class Item extends Component {
  constructor(props) {
    super(props)
    this.state = {}
  }
  changeHandler = (id)=>{
    let { checkHandler } = this.props;
    return (e)=>{
      checkHandler(id,e.target.checked)
    }
  }
  removeHandler(){
    let { delHandler } = this.props;
    delHandler(arguments[0])
  }
  editHadnler = (item)=>{
    $bus.emit("getFlag",true)
    localStorage.setItem("obj",JSON.stringify(item))
    $bus.emit("getItem",item)
  }
  render() {
    let { item } = this.props;
    return (
      <li className="task-item">
        <input type="checkbox" checked={item.checked} onChange={this.changeHandler(item.id)}/>
        <div className="content">
          {item.content}
        </div>
        <button className={`btn btn-success ${!item.checked ? "d-none" : "d-block"}`} onClick={()=> this.editHadnler(item)}>编辑</button>
        <button className={`btn btn-danger ${!item.checked ? "d-none" : "d-block"}`} onClick={this.removeHandler.bind(this,item.id)}>删除</button>
      </li>
    )
  }
}

Total.js

import React, { Component } from 'react'
export default class Total extends Component {
  constructor() {
    super()
    this.changeAllHandler = this.changeAllHandler.bind(this)
  }
  changeAllHandler(e) {
    let { checkAllHandler } = this.props
    checkAllHandler(e.target.checked)
  }
  render() {
    let { checkAll,selectLength } = this.props;
    return (
      <div className="task-done">
        <input type="checkbox" onChange={this.changeAllHandler} checked={checkAll}/>
        <p>已完成<span className="single-number">{selectLength}</span> 全部<span className="all-number">4</span></p>
      </div>
    )
  }
}

Mask.js(弹窗)

import React, { Component } from 'react'
import { bus as $bus } from './bus'
export default class mask extends Component {
  constructor() {
    super()
    this.state = {
      value: ''
    }
  }
  closeMask = ()=>{ // 关闭弹窗
    $bus.emit("getFlag",false)
  }
  updateHandler = ()=>{
    $bus.emit("getFlag",false)
    $bus.emit("update",this.state.value)
  }
  onChange = (e) =>{
    this.setState({
      value: e.target.value
    })
  }
  componentDidMount() {
    let obj = JSON.parse(localStorage.getItem("obj"))
    this.setState({
      value: obj.content
    })
  }
  render() {
    let { value } = this.state
    return (
      <div>
        <div className="mm-mask" >
        <div className="mm-modal">
          <div className="mm-title">
            <span className="mm-edit">编辑</span>
            <span className="mm-close" onClick={this.closeMask}>x</span>
          </div>
          <div className="mm-content">
            <input type="text" value={value} placeholder="任务名称" onInput={this.onChange}/>
          </div>
          <div className="mm-box-btn">
            <div className="mm-update" onClick={this.updateHandler}>更新</div>
            <div className="mm-cancel" onClick={this.closeMask}>取消</div>
          </div>
        </div>
      </div>
      </div>
    )
  }
}

bus.js

 yarn add -D events
import { EventEmitter } from 'events'
export const bus = new EventEmitter() // 导出bus实例

App.css

* {
  margin: 0;
  padding: 0;
}
input,button {
  outline: none;
  border: 0;
}
ul>li {
  list-style: none;
}
.container {
  width: 400px;
  height: 500px;
  margin: 10px auto auto;
  padding: 20px;
  box-sizing: border-box;
  color: #3333;
  border: 1px solid;
  overflow: hidden;
}
.input {
  width: 100%;
  height: 30px;
  display: flex;
}
input {
  width: 100%;
  height: 100%;
  border: 1px solid #e1e1e1;
  box-sizing: border-box;
  border-radius: 4px;
  padding: 0 10px;
}
input::placeholder {
  color: #e1e1e1;
}
input:focus {
  border: 1px solid #0096e6;
}
.task-list {
  width: 100%;
  display: flex;
  flex-flow: column wrap;
  margin-top: 10px;
}
.task-list li {
  display: flex;
  height: 40px;
  justify-content: center;
  align-items: center;
  padding: 0 10px;
  background-color: #eef0f4;
  margin-bottom: 10px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.task-list li input[type^="checkbox"] {
  width: 15px;
  height: 15px;
  border: 1px solid #e1e1e1;
  cursor: pointer;
  flex-shrink: 0;
}
.task-list li .content {
  flex: 1;
  margin-left: 10px;
}
.btn {
  flex-shrink: 0;
  display: flex;
  align-items: center;
  height: 30px;
  justify-content: center;
  padding: 5px 10px;
  text-align: center;
  cursor: pointer;
  border-radius: 4px;
  color: #fff;
  letter-spacing: 2px;
  margin: 0 5px;
  box-sizing: border-box;
  font-size: 16px;
}
.btn-success {
  background-color: #0f0;
}
.btn-danger {
  background-color: #f00;
}
.btn-primary {
  background-color: #0096e6;
}
.task-done {
  width: 100%;
  height: 40px;
  line-height: 40px;
  display: flex;
  align-items: center;
  background-color: #eef0f4;
  padding-left: 10px;
  box-sizing: border-box;
  margin-top: 30px;
}
.task-done input {
  width: 15px;
  height: 15px;
  border: 1px solid #e1e1e1;
  cursor: pointer;
  flex-shrink: 0;
  margin-right: 10px;
}
.single-number {
  color: #333;
  margin-left: 5px;
}
.all-number {
  color: red;
  margin-left: 5px;
}
.mm-mask{
  position:fixed;
  top:0;
  left:0;
  right:0;
  bottom:0;
  background:rgba(0,0,0,0.5);
}
.mm-modal{
  width:350px;
  position:absolute;
  top:50%;
  left:50%;
  transform:translate(-50%,-50%);
  z-index:1000;
  background:#ffffff;
  border-radius:4px;
  color:#333333;
}
.mm-title {
  height:50px;
  line-height:50px;
  display:flex;
  justify-content:space-between;
  border-bottom:1px solid #e1e1e1;
  box-sizing:border-box;
  font-size:20px;
}
.mm-edit{
  text-indent:20px;
}
.mm-close{
  margin-right:20px;
  font-family:consals;
  cursor:pointer;
}
.mm-content{
  padding:0 20px;
  margin-bottom:20px;
}
.mm-content input{
  width:100%;
  height:30px;
  line-height:30px;
  text-indent:20px;
  border-radius:4px;
  margin-top:20px;
  border:1px solid #666;
  box-sizing:border-box;
}
.mm-content input:hover{
  border:1px solid #0096e6;
}
.mm-content input:last-child{
  text-indent:5px;
}
.mm-box-btn{
  display:flex;
}
.mm-update,.mm-cancel{
  width:80px;
  height:30px;
  line-height:30px;
  text-align: center;
  cursor:pointer;
  background:#0096e6;
  color:#ffffff;
  user-select:none;
  border-radius:4px;
  margin:0 20px 50px;
}
.mm-update{
  margin-right:10px;
}
.d-none {
  display: none;
}
.d-block {
  display: block;
}

总结

本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注Devmax的更多内容!

react实现todolist的增删改查详解的更多相关文章

  1. ios – React native链接到另一个应用程序

    如果是错误的,有人知道如何调用正确的吗?

  2. ios – React Native – 在异步操作后导航

    我正在使用ReactNative和Redux开发移动应用程序,我正面临着软件设计问题.我想调用RESTAPI进行登录,如果该操作成功,则导航到主视图.我正在使用redux和thunk所以我已经实现了异步操作,所以我的主要疑问是:我应该把逻辑导航到主视图?我可以直接从动作访问导航器对象并在那里执行导航吗?.我对组件中的逻辑没有信心.似乎不是一个好习惯.有没有其他方法可以做到这一点?

  3. 在ios中使用带有React Native(0.43.4)的cocoapods的正确方法是什么?

    我已经挖掘了很多帖子试图使用cocoapods为本地ios库设置一个反应原生项目,但我不可避免地在#import中找到了丢失文件的错误.我的AppDelegate.m文件中的语句.什么是使用反应原生的可可豆荚的正确方法?在这篇文章发表时,我目前的RN版本是0.43.4,而我正在使用Xcode8.2.1.这是我的过程,好奇我可能会出错:1)

  4. ios – React Native WebView滚动行为无法按预期工作

    如何确保滚动事件的行为与ReactNative应用程序中的浏览器相同?

  5. ios – React Native – BVLinearGradient – 找不到’React/RCTViewManager.h’文件

    谢谢.解决方法几天前我遇到了完全相同的问题.问题是在构建应用程序时React尚未链接.试试这个:转到Product=>Scheme=>管理方案…=>点击你的应用程序Scheme,然后点击Edit=>转到Build选项卡=>取消选中ParallelizeBuild然后点击标志添加目标=>搜索React,选择第一个名为React的目标,然后单击Add然后在目标列表中选择React并将其向上拖动到该列表中的第一个.然后转到Product=>再次清理并构建项目.这应该有所帮助.

  6. ios – React Native – NSNumber无法转换为NSString

    解决方法在你的fontWeight()函数中也许变成:

  7. ios – React native error – react-native-xcode.sh:line 45:react-native:command not found命令/ bin/sh失败,退出代码127

    尝试构建任何(新的或旧的)项目时出现此错误.我的节点是版本4.2.1,react-native是版本0.1.7.我看过其他有相同问题的人,所以我已经更新了本机的最新版本,但是我仍然无法通过xcode构建任何项目.解决方法要解决此问题,请使用以下步骤:>使用节点版本v4.2.1>cd进入[你的应用]/node_modules/react-native/packager>$sh./packager.s

  8. 反应原生 – 如何通过Xcode构建React Native iOS应用程序到设备?

    我试图将AwesomeProject应用程序构建到设备上.构建成功并启动屏幕显示,但后来我看到一个红色的“无法连接到开发服务器”屏幕.它表示“确保节点服务器正在运行–从Reactroot运行”npmstart“.看起来节点服务器已经运行,因为当我做npm启动时,我收到一个EADDRINUSE消息,表示该端口已经在使用.解决方法从设备访问开发服务器您可以使用开发服务器快速迭代设备.要做到这一点,你的

  9. 静音iOS推送通知与React Native应用程序在后台

    我有一个ReactNative应用程序,我试图获得一个发送到JavaScript处理程序的静默iOS推送通知.我看到的行为是AppDelegate中的didReceiveRemoteNotification函数被调用,但是我的JavaScript中的处理程序不会被调用,除非应用程序在前台,或者最近才被关闭.我很困惑的事情显然是应用程序正在被唤醒,并且它的didReceiveRemoteNotifi

  10. 如何为iOS的React Native设置分析

    所以我已经完成了一个针对iOS的ReactNative项目,但是我想在其中分析.我尝试了react-native-google-analytics软件包,但是问题阻止了它的正常工作.此外,react-native-cordova-plugin软件包只适用于Android,因此插入Cordova插件进行分析的能力现在已成为问题.我也没有Swift/ObjectiveC的经验,所以将完全失去GA的插入.有没有人有任何建议如何连接GoogleAnalytics的ReactNativeforiOS?

随机推荐

  1. js中‘!.’是什么意思

  2. Vue如何指定不编译的文件夹和favicon.ico

    这篇文章主要介绍了Vue如何指定不编译的文件夹和favicon.ico,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

  3. 基于JavaScript编写一个图片转PDF转换器

    本文为大家介绍了一个简单的 JavaScript 项目,可以将图片转换为 PDF 文件。你可以从本地选择任何一张图片,只需点击一下即可将其转换为 PDF 文件,感兴趣的可以动手尝试一下

  4. jquery点赞功能实现代码 点个赞吧!

    点赞功能很多地方都会出现,如何实现爱心点赞功能,这篇文章主要为大家详细介绍了jquery点赞功能实现代码,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  5. AngularJs上传前预览图片的实例代码

    使用AngularJs进行开发,在项目中,经常会遇到上传图片后,需在一旁预览图片内容,怎么实现这样的功能呢?今天小编给大家分享AugularJs上传前预览图片的实现代码,需要的朋友参考下吧

  6. JavaScript面向对象编程入门教程

    这篇文章主要介绍了JavaScript面向对象编程的相关概念,例如类、对象、属性、方法等面向对象的术语,并以实例讲解各种术语的使用,非常好的一篇面向对象入门教程,其它语言也可以参考哦

  7. jQuery中的通配符选择器使用总结

    通配符在控制input标签时相当好用,这里简单进行了jQuery中的通配符选择器使用总结,需要的朋友可以参考下

  8. javascript 动态调整图片尺寸实现代码

    在自己的网站上更新文章时一个比较常见的问题是:文章插图太宽,使整个网页都变形了。如果对每个插图都先进行缩放再插入的话,太麻烦了。

  9. jquery ajaxfileupload异步上传插件

    这篇文章主要为大家详细介绍了jquery ajaxfileupload异步上传插件,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  10. React学习之受控组件与数据共享实例分析

    这篇文章主要介绍了React学习之受控组件与数据共享,结合实例形式分析了React受控组件与组件间数据共享相关原理与使用技巧,需要的朋友可以参考下

返回
顶部