react+react-beautiful-dnd实例代办事项_ react-beautiful-dnd教程(2)

文章详细描述了一个使用React和react-beautiful-dnd库实现的TodoList组件,涉及状态管理、拖放功能、以及根据不同选择过滤已完成和未完成事项。还提到了如何通过提供者组件和上下文API进行数据传递和状态更新。
摘要由CSDN通过智能技术生成
allCheckbox=(status)=>{
    this.setState({
        todos:this.state.todos.map(todo=>{
            todo.completed=status
            return todo
        })
    })
}
// 删除已完成事件
delCompelted=()=>{
    this.setState({
        todos:this.state.todos.filter(todo=>!todo.completed)
    })
}
render() {
    return(
        <Provider value={{
            todos:this.state.todos,
            changComple:this.changComple,
            delTodo:this.delTodo,
            allCheckbox:this.allCheckbox,
            delCompelted:this.delCompelted,
        }}>
            <article className="panel is-success">
                <TodoHeader/>
                <TodoInput add={this.addTodoItem}/>
                <TodoList todos={this.state.todos} drag={this.drag.bind(this)}/>
                <TodoFoot/>

            </article>
        </Provider>

    )
}

}


#### untils/with-context.js封装工具todoContext



import {createContext} from “react”;
// 创建creatContext对象
const TodoContext = createContext()
// 结构要用到的React组件
const {
Provider, // 生产组件
Consumer, // 消费组件
} = TodoContext
export {
Provider,
Consumer,
TodoContext,
}


* components/TodoHeader.jsx页面头部



import React, { Component } from ‘react’

export default class TodoHeader extends Component {
render() {
return (


待办事项列表


)
}
}

#### components/TodoInput.jsx该文件主要负责添加事件



import React, {Component, createRef} from “react”;
export default class TodoInput extends Component{
state={
inputValue:‘输入代办事件’, // 定义input输入框内容
}
inputRef=createRef() // 定义ref绑定DOM元素,作用是为下面自动获取焦点做准备
// 输入框中输入的内容设置给state作用1:输入框内容改变2:后面提交添加事件拿到input内容
handleChang=Event=>{
this.setState({
inputValue:Event.target.value
})
}
// 添加代办事件
handleDown=Event=>{
// 验证下是否为空
if(this.state.inputValue===‘’ || this.state.inputValue===null) return
if(Event.keyCode ===13){
this.add()
}
}
// 添加处理函数
add=()=>{
// add方法通过props从App传入
this.props.add(this.state.inputValue)
this.state.inputValue=‘’
// ref绑定后通过inputRef.current拿到DOM元素
this.inputRef.current.focus()
}
render() {
return(



<input
className=“input is-success”
type=“text”
placeholder=“输入代办事项”
value={this.state.inputValue}
onChange={this.handleChang}
onKeyDown={this.handleDown.bind(this)} //该变this指向
ref={this.inputRef}
/>



)
}
}


#### 介绍下[react-beautiful-dnd](https://bbs.csdn.net/topics/618545628)处理函数


* 官方解析图  
 ![请添加图片描述](https://img-blog.csdnimg.cn/401a588ad7f64b2a80cf948255b29292.gif)
* 格式DragDropContext最外面盒子Droppable第二层盒子



{provided=>( <\* ref={provided.innerRef} {...provided.droppableProps} // 官方固定格式 > 自己的代码 <\*/> {provided.placeholder} )}

* 格式Draggable最里面盒子



{provided=>( <\* {...provided.draggableProps} {...provided.dragHandleProps} ref={provided.innerRef} > 自己的代码 <\*/> {provided.placeholder} )}

* 一但移动(从第5个事件移动到第4个事件)onDragEnd回调函数打印结果console.log(result)



{draggableId: ‘5’, type: ‘DEFAULT’, source: {…}, reason: ‘DROP’, mode: ‘FLUID’, …}
combine: null
destination: {droppableId: ‘columns’, index: 4} // 移动到第4个事件
draggableId: “5”
mode: “FLUID”
reason: “DROP”
source: {index: 5, droppableId: ‘columns’} // 移动的第5个事件
type: “DEFAULT”
[[Prototype]]: Object


#### components/TodoList.jsx



import React,{Component} from “react”;
import TodoItem from “./TodoItem”;
import PropTypes from ‘prop-types’
import {DragDropContext} from ‘react-beautiful-dnd’
import {Droppable} from ‘react-beautiful-dnd’

export default class TodoList extends Component{
// 类型检查
static propTypes={
todos:PropTypes.array.isRequired,
}
// 默认值
static defaultProps = {
todos: [],
}
// 根据choice数值决定渲染事项
state={
choice:1
}
// react-beautiful-dnd核心处理函数,负责交换后的处理(可以自定义)
onDragEnd=result=>{
console.log(result)
const {destination,source,draggableId}=result
if(!destination){ // 移动到了视图之外
return
}
if( // 移动到原来位置,也就是位置不变
destination.droppableId=source.droppableId &&
destination.index
=source.index
){ return;}
const newTaskIds=Array.from(this.props.todos) // 转化为真正的数组
newTaskIds.splice(source.index,1) // 删除移动的数组
newTaskIds.splice(destination.index,0,this.props.todos[source.index]) // 在移动到的位置初放置被删除的数组

    // 调用App文件中的drag执行交换后的更改
    this.props.drag(newTaskIds)

}
// 点击时渲染不同DOM
choice=(num)=>{
    this.setState({
        choice:num
    })
}
render() {
    let uls=null
    if(this.state.choice===1){
        uls=(<DragDropContext onDragEnd={this.onDragEnd}>
                <Droppable droppableId='columns'>
                    {provided=>(
                        <ul
                            ref={provided.innerRef}
                            {...provided.droppableProps}
                        >
                            {this.props.todos.length>0
                                ? this.props.todos.map((todo,index)=>{
                                    return (
                                        <TodoItem key={todo.id} todo={todo} index={index}/>
                                    )
                                })
                                :<div>添加代办事项</div>

                            }
                            {provided.placeholder}
                        </ul>
                    )}

                </Droppable>

            </DragDropContext>)
    }else if(this.state.choice===2){
        // 过滤下事件
        let newtodos=this.props.todos.filter(todo=> todo.completed)
            uls=(<DragDropContext onDragEnd={this.onDragEnd}>
                <Droppable droppableId='columns'>
                    {provided=>(
                        <ul
                            ref={provided.innerRef}
                            {...provided.droppableProps}
                        >
                            {newtodos.length>0
                                ? newtodos.map((todo,index)=>{
                                    return (
                                        <TodoItem key={todo.id} todo={todo} index={index}/>
                                    )
                                })
                                :<div>暂无已完成事件</div>

                            }
                            {provided.placeholder}
                        </ul>
                    )}

                </Droppable>

            </DragDropContext>)
    }else if(this.state.choice===3){
        // 过滤下事件
        let newtodos=this.props.todos.filter(todo=> !todo.completed)
        uls=(<DragDropContext onDragEnd={this.onDragEnd}>
            <Droppable droppableId='columns'>
                {provided=>(
                    <ul
                        ref={provided.innerRef}
                        {...provided.droppableProps}
                    >
                        {newtodos.length>0
                            ? newtodos.map((todo,index)=>{
                                return (
                                    <TodoItem key={todo.id} todo={todo} index={index}/>
                                )
                            })
                            :<div>暂无未完成事件</div>

                        }
                        {provided.placeholder}
                    </ul>
                )}

            </Droppable>

        </DragDropContext>)
    }
    return(
        <>
               <p className="panel-tabs">
                     <a className="is-active" onClick={()=>this.choice(1)}>所有</a>
                     <a onClick={()=>this.choice(2)}>已完成</a>
                     <a onClick={()=>this.choice(3)}>未完成</a>
                </p>
              {uls}
        </>
    )
}

}



![img](https://img-blog.csdnimg.cn/img_convert/ffef963e978612e3c480c84b46826971.png)
![外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传](https://img-home.csdnimg.cn/images/20230724024159.png?origin_url=https%3A%2F%2Fimg-community.csdnimg.cn%2Fimages%2F00bce1e6a36742d2b47b7fc3db6edc8f.png&pos_id=img-1eaDe6UG-1714710507042)

**网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。**

**[需要这份系统化资料的朋友,可以戳这里获取](https://bbs.csdn.net/topics/618545628)**


**一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!**

   )
    }
}

[外链图片转存中…(img-a2wdwLei-1714710507041)]
[外链图片转存中…(img-1eaDe6UG-1714710507042)]

网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。

需要这份系统化资料的朋友,可以戳这里获取

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

  • 26
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值